repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
GoogleCloudPlatform/dataflow-ordered-processing
beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedEventProcessor.java
[ { "identifier": "Builder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@AutoValue.Builder\npublic abstract static class Builder {\n\n public abstract Builder setSequenceNumber(long value);\n\n public abstract Builder setReceivedOrder(long value);\n\n public abstract Builder setProcessingTime(Instant value);\n\n public abstract Builder setEventBufferedTime(Instant value);\n\n public abstract Builder setQueriedBufferedEvents(QueriedBufferedEvents value);\n\n public abstract Builder setClearedBufferedEvents(ClearedBufferedEvents value);\n\n public abstract OrderedProcessingDiagnosticEvent build();\n}" }, { "identifier": "ClearedBufferedEvents", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@DefaultSchema(AutoValueSchema.class)\n@AutoValue\npublic abstract static class ClearedBufferedEvents {\n\n public static ClearedBufferedEvents create(Instant rangeStart, Instant rangeEnd) {\n return builder().setRangeStart(rangeStart).setRangeEnd(rangeEnd).build();\n }\n\n public abstract Instant getRangeStart();\n\n public abstract Instant getRangeEnd();\n\n public static Builder builder() {\n return new AutoValue_OrderedProcessingDiagnosticEvent_ClearedBufferedEvents.Builder();\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setRangeStart(Instant value);\n\n public abstract Builder setRangeEnd(Instant value);\n\n public abstract ClearedBufferedEvents build();\n }\n}" }, { "identifier": "QueriedBufferedEvents", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@DefaultSchema(AutoValueSchema.class)\n@AutoValue\npublic abstract static class QueriedBufferedEvents {\n\n public static QueriedBufferedEvents create(Instant queryStart, Instant queryEnd,\n Instant firstReturnedEvent) {\n return builder().setQueryStart(queryStart).setQueryEnd(queryEnd)\n .setFirstReturnedEvent(firstReturnedEvent).build();\n }\n\n public abstract Instant getQueryStart();\n\n public abstract Instant getQueryEnd();\n\n @Nullable\n public abstract Instant getFirstReturnedEvent();\n\n public static Builder builder() {\n return new org.apache.beam.sdk.extensions.ordered.AutoValue_OrderedProcessingDiagnosticEvent_QueriedBufferedEvents.Builder();\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setQueryStart(Instant value);\n\n public abstract Builder setQueryEnd(Instant value);\n\n public abstract Builder setFirstReturnedEvent(Instant value);\n\n public abstract QueriedBufferedEvents build();\n }\n}" }, { "identifier": "ProcessingStateCoder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/ProcessingState.java", "snippet": "static class ProcessingStateCoder<KeyT> extends Coder<ProcessingState<KeyT>> {\n\n private static final NullableCoder<Long> NULLABLE_LONG_CODER = NullableCoder.of(\n VarLongCoder.of());\n private static final Coder<Long> LONG_CODER = VarLongCoder.of();\n private static final VarIntCoder INTEGER_CODER = VarIntCoder.of();\n private static final BooleanCoder BOOLEAN_CODER = BooleanCoder.of();\n\n private Coder<KeyT> keyCoder;\n\n public static <KeyT> ProcessingStateCoder<KeyT> of(Coder<KeyT> keyCoder) {\n ProcessingStateCoder<KeyT> result = new ProcessingStateCoder<>();\n result.keyCoder = keyCoder;\n return result;\n }\n\n @Override\n public void encode(ProcessingState<KeyT> value, OutputStream outStream) throws IOException {\n NULLABLE_LONG_CODER.encode(value.getLastOutputSequence(), outStream);\n NULLABLE_LONG_CODER.encode(value.getEarliestBufferedSequence(), outStream);\n NULLABLE_LONG_CODER.encode(value.getLatestBufferedSequence(), outStream);\n LONG_CODER.encode(value.getBufferedRecordCount(), outStream);\n LONG_CODER.encode(value.getRecordsReceived(), outStream);\n LONG_CODER.encode(value.getDuplicates(), outStream);\n LONG_CODER.encode(value.getResultCount(), outStream);\n BOOLEAN_CODER.encode(value.isLastEventReceived(), outStream);\n keyCoder.encode(value.getKey(), outStream);\n }\n\n @Override\n public ProcessingState<KeyT> decode(InputStream inStream) throws IOException {\n Long lastOutputSequence = NULLABLE_LONG_CODER.decode(inStream);\n Long earliestBufferedSequence = NULLABLE_LONG_CODER.decode(inStream);\n Long latestBufferedSequence = NULLABLE_LONG_CODER.decode(inStream);\n int bufferedRecordCount = INTEGER_CODER.decode(inStream);\n long recordsReceivedCount = LONG_CODER.decode(inStream);\n long duplicates = LONG_CODER.decode(inStream);\n long resultCount = LONG_CODER.decode(inStream);\n boolean isLastEventReceived = BOOLEAN_CODER.decode(inStream);\n KeyT key = keyCoder.decode(inStream);\n\n return new ProcessingState<>(key, lastOutputSequence, earliestBufferedSequence,\n latestBufferedSequence, bufferedRecordCount, recordsReceivedCount, duplicates,\n resultCount, isLastEventReceived);\n }\n\n @Override\n public List<? extends Coder<?>> getCoderArguments() {\n return List.of();\n }\n\n @Override\n public void verifyDeterministic() {\n }\n}" }, { "identifier": "Reason", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/UnprocessedEvent.java", "snippet": "public enum Reason {duplicate, buffered}" }, { "identifier": "UnprocessedEventCoder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/UnprocessedEvent.java", "snippet": " static class UnprocessedEventCoder<EventT> extends Coder<UnprocessedEvent<EventT>> {\n\n private final Coder<EventT> eventCoder;\n\n UnprocessedEventCoder(Coder<EventT> eventCoder) {\n this.eventCoder = eventCoder;\n }\n\n @Override\n public void encode(UnprocessedEvent<EventT> value, OutputStream outStream) throws IOException {\n ByteCoder.of().encode((byte) value.getReason().ordinal(), outStream);\n eventCoder.encode(value.getEvent(), outStream);\n }\n\n @Override\n public UnprocessedEvent<EventT> decode(InputStream inputStream) throws IOException {\n Reason reason = Reason.values()[ByteCoder.of().decode(inputStream)];\n EventT event = eventCoder.decode(inputStream);\n return UnprocessedEvent.create(event, reason);\n }\n\n @Override\n public List<? extends Coder<?>> getCoderArguments() {\n// TODO: implement\n return null;\n }\n\n @Override\n public void verifyDeterministic() throws NonDeterministicException {\n// TODO: implement\n }\n }" } ]
import com.google.auto.value.AutoValue; import java.util.Arrays; import java.util.Iterator; import javax.annotation.Nullable; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.BooleanCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.VarLongCoder; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.Builder; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.ClearedBufferedEvents; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.QueriedBufferedEvents; import org.apache.beam.sdk.extensions.ordered.ProcessingState.ProcessingStateCoder; import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.Reason; import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.UnprocessedEventCoder; import org.apache.beam.sdk.schemas.NoSuchSchemaException; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.schemas.SchemaRegistry; import org.apache.beam.sdk.state.OrderedListState; import org.apache.beam.sdk.state.StateSpec; import org.apache.beam.sdk.state.StateSpecs; import org.apache.beam.sdk.state.TimeDomain; import org.apache.beam.sdk.state.Timer; import org.apache.beam.sdk.state.TimerSpec; import org.apache.beam.sdk.state.TimerSpecs; import org.apache.beam.sdk.state.ValueState; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollection.IsBounded; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.TimestampedValue; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; import org.apache.beam.sdk.values.TypeDescriptor; import org.joda.time.Duration; import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
4,622
} if (processingState.isNextEvent(currentSequence)) { // Event matches expected sequence state = currentStateState.read(); state.mutate(currentEvent); Result result = state.produceResult(); if (result != null) { outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result)); processingState.resultProduced(); } processingState.eventAccepted(currentSequence, thisIsTheLastEvent); return state; } // Event is not ready to be processed yet Instant eventTimestamp = Instant.ofEpochMilli(currentSequence); bufferedEventsState.add(TimestampedValue.of(currentEvent, eventTimestamp)); processingState.eventBuffered(currentSequence, thisIsTheLastEvent); diagnostics.setEventBufferedTime(eventTimestamp); // This will signal that the state hasn't been mutated and we don't need to save it. return null; } /** * Process buffered events * * @param processingState * @param state * @param bufferedEventsState * @param outputReceiver * @param largeBatchEmissionTimer * @param diagnostics */ private void processBufferedEvents(ProcessingState<EventKey> processingState, State state, OrderedListState<Event> bufferedEventsState, MultiOutputReceiver outputReceiver, Timer largeBatchEmissionTimer, Builder diagnostics) { if (state == null) { // Only when the current event caused a state mutation and the state is passed to this // method should we attempt to process buffered events return; } if (!processingState.readyToProcessBufferedEvents()) { return; } if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) { // No point in trying to process buffered events return; } int recordCount = 0; Instant firstEventRead = null; Instant startRange = Instant.ofEpochMilli(processingState.getEarliestBufferedSequence()); Instant endRange = Instant.ofEpochMilli(processingState.getLatestBufferedSequence() + 1); Instant endClearRange = null; // readRange is efficiently implemented and will bring records in batches Iterable<TimestampedValue<Event>> events = bufferedEventsState.readRange(startRange, endRange); Iterator<TimestampedValue<Event>> bufferedEventsIterator = events.iterator(); while (bufferedEventsIterator.hasNext()) { TimestampedValue<Event> timestampedEvent = bufferedEventsIterator.next(); Instant eventTimestamp = timestampedEvent.getTimestamp(); long eventSequence = eventTimestamp.getMillis(); if (recordCount++ == 0) { firstEventRead = eventTimestamp; } Event bufferedEvent = timestampedEvent.getValue(); if (processingState.checkForDuplicateBatchedEvent(eventSequence)) { outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(), KV.of(eventSequence, UnprocessedEvent.create(bufferedEvent, Reason.duplicate)))); continue; } if (eventSequence > processingState.getLastOutputSequence() + 1) { processingState.foundSequenceGap(eventSequence); // Records will be cleared up to this element endClearRange = Instant.ofEpochMilli(eventSequence); break; } // This check needs to be done after we checked for sequence gap and before we // attempt to process the next element which can result in a new result. if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) { endClearRange = Instant.ofEpochMilli(eventSequence); break; } state.mutate(bufferedEvent); Result result = state.produceResult(); if (result != null) { outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result)); processingState.resultProduced(); } processingState.processedBufferedEvent(eventSequence); // Remove this record also endClearRange = Instant.ofEpochMilli(eventSequence + 1); } // Temporarily disabled due to https://github.com/apache/beam/pull/28171 // bufferedEventsState.clearRange(startRange, endClearRange); // TODO: Draining events is a temporary workaround related to https://github.com/apache/beam/issues/28370 // It can be removed once https://github.com/apache/beam/pull/28371 is available in a regular release while (bufferedEventsIterator.hasNext()) { // Read and discard all events bufferedEventsIterator.next(); } diagnostics.setQueriedBufferedEvents( QueriedBufferedEvents.create(startRange, endRange, firstEventRead));
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.ordered; /** * Transform for processing ordered events. Events are grouped by the key and within each key they * are applied according to the provided sequence. Events which arrive out of sequence are buffered * and reprocessed when new events for a given key arrived. * * @param <Event> * @param <EventKey> * @param <State> */ @AutoValue @SuppressWarnings({"nullness", "TypeNameShadowing"}) public abstract class OrderedEventProcessor<Event, EventKey, Result, State extends MutableState<Event, Result>> extends PTransform<PCollection<KV<EventKey, KV<Long, Event>>>, OrderedEventProcessorResult<EventKey, Result, Event>> { public static final int DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS = 5; public static final boolean DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS = false; private static final boolean DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT = false; public static final int DEFAULT_MAX_ELEMENTS_TO_OUTPUT = 10_000; public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create( EventExaminer<EventType, StateType> eventExaminer, Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultTypeCoder) { return new AutoValue_OrderedEventProcessor<>(eventExaminer, null /* no event coder */, stateCoder, keyCoder, resultTypeCoder, DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT, DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT); } /** * Default constructor method * * @param <EventType> * @param <KeyType> * @param <StateType> * @param eventCoder coder for the Event class * @param keyCoder coder for the Key class * @param stateCoder coder for the State class * @param resultCoder * @return */ public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create( EventExaminer<EventType, StateType> eventExaminer, Coder<EventType> eventCoder, Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultCoder) { // TODO: none of the values are marked as @Nullable and the transform will fail if nulls are provided. But need a better error messaging. return new AutoValue_OrderedEventProcessor<>(eventExaminer, eventCoder, stateCoder, keyCoder, resultCoder, DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT, DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT); } /** * Provide a custom status update frequency * * @param seconds * @return */ public OrderedEventProcessor<Event, EventKey, Result, State> withStatusUpdateFrequencySeconds( int seconds) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), seconds, this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(), this.getMaxNumberOfResultsPerOutput()); } public OrderedEventProcessor<Event, EventKey, Result, State> produceDiagnosticEvents( boolean produceDiagnosticEvents) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(), produceDiagnosticEvents, this.getMaxNumberOfResultsPerOutput()); } /** * Notice that unless the status frequency update is set to 0 or negative number the status will * be produced on every event and with the specified frequency. */ public OrderedEventProcessor<Event, EventKey, Result, State> produceStatusUpdatesOnEveryEvent( boolean value) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), value, this.isProduceDiagnosticEvents(), this.getMaxNumberOfResultsPerOutput()); } public OrderedEventProcessor<Event, EventKey, Result, State> withMaxResultsPerOutput( long maxResultsPerOutput) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(), maxResultsPerOutput); } abstract EventExaminer<Event, State> getEventExaminer(); @Nullable abstract Coder<Event> getEventCoder(); abstract Coder<State> getStateCoder(); @Nullable abstract Coder<EventKey> getKeyCoder(); abstract Coder<Result> getResultCoder(); abstract int getStatusUpdateFrequencySeconds(); abstract boolean isProduceStatusUpdateOnEveryEvent(); abstract boolean isProduceDiagnosticEvents(); abstract long getMaxNumberOfResultsPerOutput(); @Override public OrderedEventProcessorResult<EventKey, Result, Event> expand( PCollection<KV<EventKey, KV<Long, Event>>> input) { final TupleTag<KV<EventKey, Result>> mainOutput = new TupleTag<>("mainOutput") { }; final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusOutput = new TupleTag<>("status") { }; final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticOutput = new TupleTag<>( "diagnostics") { }; final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventOutput = new TupleTag<>( "unprocessed-events") { }; Coder<EventKey> keyCoder = getKeyCoder(); if (keyCoder == null) { // Assume that the default key coder is used and use the key coder from it. keyCoder = ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getKeyCoder(); } Coder<Event> eventCoder = getEventCoder(); if (eventCoder == null) { // Assume that the default key coder is used and use the event coder from it. eventCoder = ((KvCoder<Long, Event>) ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getValueCoder()).getValueCoder(); } PCollectionTuple processingResult = input.apply(ParDo.of( new OrderedProcessorDoFn<>(getEventExaminer(), eventCoder, getStateCoder(), keyCoder, mainOutput, statusOutput, getStatusUpdateFrequencySeconds() <= 0 ? null : Duration.standardSeconds(getStatusUpdateFrequencySeconds()), diagnosticOutput, unprocessedEventOutput, isProduceDiagnosticEvents(), isProduceStatusUpdateOnEveryEvent(), input.isBounded() == IsBounded.BOUNDED ? Integer.MAX_VALUE : getMaxNumberOfResultsPerOutput())).withOutputTags(mainOutput, TupleTagList.of(Arrays.asList(statusOutput, diagnosticOutput, unprocessedEventOutput)))); KvCoder<EventKey, Result> mainOutputCoder = KvCoder.of(keyCoder, getResultCoder()); KvCoder<EventKey, OrderedProcessingStatus> processingStatusCoder = KvCoder.of(keyCoder, getOrderedProcessingStatusCoder(input.getPipeline())); KvCoder<EventKey, OrderedProcessingDiagnosticEvent> diagnosticOutputCoder = KvCoder.of(keyCoder, getOrderedProcessingDiagnosticsCoder(input.getPipeline())); KvCoder<EventKey, KV<Long, UnprocessedEvent<Event>>> unprocessedEventsCoder = KvCoder.of( keyCoder, KvCoder.of(VarLongCoder.of(), new UnprocessedEventCoder<>(eventCoder))); return new OrderedEventProcessorResult<>( input.getPipeline(), processingResult.get(mainOutput).setCoder(mainOutputCoder), mainOutput, processingResult.get(statusOutput).setCoder(processingStatusCoder), statusOutput, processingResult.get(diagnosticOutput).setCoder(diagnosticOutputCoder), diagnosticOutput, processingResult.get(unprocessedEventOutput).setCoder(unprocessedEventsCoder), unprocessedEventOutput); } private static Coder<OrderedProcessingStatus> getOrderedProcessingStatusCoder(Pipeline pipeline) { SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry(); Coder<OrderedProcessingStatus> result; try { result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingStatus.class), TypeDescriptor.of(OrderedProcessingStatus.class), schemaRegistry.getToRowFunction(OrderedProcessingStatus.class), schemaRegistry.getFromRowFunction(OrderedProcessingStatus.class)); } catch (NoSuchSchemaException e) { throw new RuntimeException(e); } return result; } private static Coder<OrderedProcessingDiagnosticEvent> getOrderedProcessingDiagnosticsCoder( Pipeline pipeline) { SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry(); Coder<OrderedProcessingDiagnosticEvent> result; try { result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingDiagnosticEvent.class), TypeDescriptor.of(OrderedProcessingDiagnosticEvent.class), schemaRegistry.getToRowFunction(OrderedProcessingDiagnosticEvent.class), schemaRegistry.getFromRowFunction(OrderedProcessingDiagnosticEvent.class)); } catch (NoSuchSchemaException e) { throw new RuntimeException(e); } return result; } /** * Main DoFn for processing ordered events * * @param <Event> * @param <EventKey> * @param <State> */ static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> { private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class); private static final String PROCESSING_STATE = "processingState"; private static final String MUTABLE_STATE = "mutableState"; private static final String BUFFERED_EVENTS = "bufferedEvents"; private static final String STATUS_EMISSION_TIMER = "statusTimer"; private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer"; private static final String WINDOW_CLOSED = "windowClosed"; private final EventExaminer<Event, State> eventExaminer; @StateId(BUFFERED_EVENTS) @SuppressWarnings("unused") private final StateSpec<OrderedListState<Event>> bufferedEventsSpec; @StateId(PROCESSING_STATE) @SuppressWarnings("unused") private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec; @SuppressWarnings("unused") @StateId(MUTABLE_STATE) private final StateSpec<ValueState<State>> mutableStateSpec; @StateId(WINDOW_CLOSED) @SuppressWarnings("unused") private final StateSpec<ValueState<Boolean>> windowClosedSpec; @TimerId(STATUS_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME); @TimerId(LARGE_BATCH_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME); private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag; private final Duration statusUpdateFrequency; private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag; private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag; private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag; private final boolean produceDiagnosticEvents; private final boolean produceStatusUpdateOnEveryEvent; private final long maxNumberOfResultsToProduce; private Long numberOfResultsBeforeBundleStart; /** * Stateful DoFn to do the bulk of processing * * @param eventExaminer * @param eventCoder * @param stateCoder * @param keyCoder * @param mainOutputTupleTag * @param statusTupleTag * @param statusUpdateFrequency * @param diagnosticEventsTupleTag * @param unprocessedEventTupleTag * @param produceDiagnosticEvents * @param produceStatusUpdateOnEveryEvent * @param maxNumberOfResultsToProduce */ OrderedProcessorDoFn( EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder, Coder<State> stateCoder, Coder<EventKey> keyCoder, TupleTag<KV<EventKey, Result>> mainOutputTupleTag, TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag, Duration statusUpdateFrequency, TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag, TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag, boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent, long maxNumberOfResultsToProduce) { this.eventExaminer = eventExaminer; this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder); this.mutableStateSpec = StateSpecs.value(stateCoder); this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder)); this.windowClosedSpec = StateSpecs.value(BooleanCoder.of()); this.mainOutputTupleTag = mainOutputTupleTag; this.statusTupleTag = statusTupleTag; this.unprocessedEventsTupleTag = unprocessedEventTupleTag; this.statusUpdateFrequency = statusUpdateFrequency; this.diagnosticEventsTupleTag = diagnosticEventsTupleTag; this.produceDiagnosticEvents = produceDiagnosticEvents; this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent; this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce; } @StartBundle public void onBundleStart() { numberOfResultsBeforeBundleStart = null; } @FinishBundle public void onBundleFinish() { // This might be necessary because this field is also used in a Timer numberOfResultsBeforeBundleStart = null; } @ProcessElement public void processElement( @StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState, @AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState, @StateId(MUTABLE_STATE) ValueState<State> mutableStateState, @TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer, @TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer, @Element KV<EventKey, KV<Long, Event>> eventAndSequence, MultiOutputReceiver outputReceiver, BoundedWindow window) { // TODO: should we make diagnostics generation optional? OrderedProcessingDiagnosticEvent.Builder diagnostics = OrderedProcessingDiagnosticEvent.builder(); diagnostics.setProcessingTime(Instant.now()); EventKey key = eventAndSequence.getKey(); long sequence = eventAndSequence.getValue().getKey(); Event event = eventAndSequence.getValue().getValue(); diagnostics.setSequenceNumber(sequence); ProcessingState<EventKey> processingState = processingStateState.read(); if (processingState == null) { // This is the first time we see this key/window pair processingState = new ProcessingState<>(key); if (statusUpdateFrequency != null) { // Set up the timer to produce the status of the processing on a regular basis statusEmissionTimer.offset(statusUpdateFrequency).setRelative(); } } if (numberOfResultsBeforeBundleStart == null) { // Per key processing is synchronized by Beam. There is no need to have it here. numberOfResultsBeforeBundleStart = processingState.getResultCount(); } processingState.recordReceived(); diagnostics.setReceivedOrder(processingState.getRecordsReceived()); State state = processNewEvent(sequence, event, processingState, mutableStateState, bufferedEventsState, outputReceiver, diagnostics); processBufferedEvents(processingState, state, bufferedEventsState, outputReceiver, largeBatchEmissionTimer, diagnostics); saveStatesAndOutputDiagnostics(processingStateState, processingState, mutableStateState, state, outputReceiver, diagnostics, key, window.maxTimestamp()); checkIfProcessingIsCompleted(processingState); } private boolean checkIfProcessingIsCompleted(ProcessingState<EventKey> processingState) { boolean result = processingState.isProcessingCompleted(); if (result) { LOG.info("Processing for key '" + processingState.getKey() + "' is completed."); } return result; } private void saveStatesAndOutputDiagnostics( ValueState<ProcessingState<EventKey>> processingStatusState, ProcessingState<EventKey> processingStatus, ValueState<State> currentStateState, State state, MultiOutputReceiver outputReceiver, Builder diagnostics, EventKey key, Instant windowTimestamp) { // There is always a change to the processing status processingStatusState.write(processingStatus); // Stored state may not have changes if the element was out of sequence. if (state != null) { currentStateState.write(state); } if (produceDiagnosticEvents) { outputReceiver.get(diagnosticEventsTupleTag).output(KV.of(key, diagnostics.build())); } if (produceStatusUpdateOnEveryEvent) { // During pipeline draining the window timestamp is set to a large value in the future. // Producing an event before that results in error, that's why this logic exist. Instant statusTimestamp = Instant.now(); statusTimestamp = statusTimestamp.isAfter(windowTimestamp) ? statusTimestamp : windowTimestamp; emitProcessingStatus(processingStatus, outputReceiver, statusTimestamp); } } private void emitProcessingStatus(ProcessingState<EventKey> processingState, MultiOutputReceiver outputReceiver, Instant statusTimestamp) { outputReceiver.get(statusTupleTag).outputWithTimestamp(KV.of(processingState.getKey(), OrderedProcessingStatus.create(processingState.getLastOutputSequence(), processingState.getBufferedRecordCount(), processingState.getEarliestBufferedSequence(), processingState.getLatestBufferedSequence(), processingState.getRecordsReceived(), processingState.getResultCount(), processingState.getDuplicates(), processingState.isLastEventReceived())), statusTimestamp); } /** * Process the just received event * * @param currentSequence * @param currentEvent * @param processingState * @param currentStateState * @param bufferedEventsState * @param outputReceiver * @param diagnostics * @return */ private State processNewEvent(long currentSequence, Event currentEvent, ProcessingState<EventKey> processingState, ValueState<State> currentStateState, OrderedListState<Event> bufferedEventsState, MultiOutputReceiver outputReceiver, Builder diagnostics) { if (currentSequence == Long.MAX_VALUE) { LOG.error("Received an event with " + currentSequence + " as the sequence number. " + "It will be dropped because it needs to be less than Long.MAX_VALUE."); return null; } if (processingState.hasAlreadyBeenProcessed(currentSequence)) { outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(), KV.of(currentSequence, UnprocessedEvent.create(currentEvent, Reason.duplicate)))); return null; } State state; boolean thisIsTheLastEvent = eventExaminer.isLastEvent(currentSequence, currentEvent); if (eventExaminer.isInitialEvent(currentSequence, currentEvent)) { // First event of the key/window // What if it's a duplicate event - it will reset everything. Shall we drop/DLQ anything that's before // the processingState.lastOutputSequence? try { state = eventExaminer.createStateOnInitialEvent(currentEvent); } catch (Exception e) { // TODO: Handle exception in a better way - DLQ. // Initial state creator can be pretty heavy - remote calls, etc.. throw new RuntimeException(e); } processingState.eventAccepted(currentSequence, thisIsTheLastEvent); Result result = state.produceResult(); if (result != null) { outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result)); processingState.resultProduced(); } // Nothing else to do. We will attempt to process buffered events later. return state; } if (processingState.isNextEvent(currentSequence)) { // Event matches expected sequence state = currentStateState.read(); state.mutate(currentEvent); Result result = state.produceResult(); if (result != null) { outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result)); processingState.resultProduced(); } processingState.eventAccepted(currentSequence, thisIsTheLastEvent); return state; } // Event is not ready to be processed yet Instant eventTimestamp = Instant.ofEpochMilli(currentSequence); bufferedEventsState.add(TimestampedValue.of(currentEvent, eventTimestamp)); processingState.eventBuffered(currentSequence, thisIsTheLastEvent); diagnostics.setEventBufferedTime(eventTimestamp); // This will signal that the state hasn't been mutated and we don't need to save it. return null; } /** * Process buffered events * * @param processingState * @param state * @param bufferedEventsState * @param outputReceiver * @param largeBatchEmissionTimer * @param diagnostics */ private void processBufferedEvents(ProcessingState<EventKey> processingState, State state, OrderedListState<Event> bufferedEventsState, MultiOutputReceiver outputReceiver, Timer largeBatchEmissionTimer, Builder diagnostics) { if (state == null) { // Only when the current event caused a state mutation and the state is passed to this // method should we attempt to process buffered events return; } if (!processingState.readyToProcessBufferedEvents()) { return; } if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) { // No point in trying to process buffered events return; } int recordCount = 0; Instant firstEventRead = null; Instant startRange = Instant.ofEpochMilli(processingState.getEarliestBufferedSequence()); Instant endRange = Instant.ofEpochMilli(processingState.getLatestBufferedSequence() + 1); Instant endClearRange = null; // readRange is efficiently implemented and will bring records in batches Iterable<TimestampedValue<Event>> events = bufferedEventsState.readRange(startRange, endRange); Iterator<TimestampedValue<Event>> bufferedEventsIterator = events.iterator(); while (bufferedEventsIterator.hasNext()) { TimestampedValue<Event> timestampedEvent = bufferedEventsIterator.next(); Instant eventTimestamp = timestampedEvent.getTimestamp(); long eventSequence = eventTimestamp.getMillis(); if (recordCount++ == 0) { firstEventRead = eventTimestamp; } Event bufferedEvent = timestampedEvent.getValue(); if (processingState.checkForDuplicateBatchedEvent(eventSequence)) { outputReceiver.get(unprocessedEventsTupleTag).output(KV.of(processingState.getKey(), KV.of(eventSequence, UnprocessedEvent.create(bufferedEvent, Reason.duplicate)))); continue; } if (eventSequence > processingState.getLastOutputSequence() + 1) { processingState.foundSequenceGap(eventSequence); // Records will be cleared up to this element endClearRange = Instant.ofEpochMilli(eventSequence); break; } // This check needs to be done after we checked for sequence gap and before we // attempt to process the next element which can result in a new result. if (exceededMaxResultCountForBundle(processingState, largeBatchEmissionTimer)) { endClearRange = Instant.ofEpochMilli(eventSequence); break; } state.mutate(bufferedEvent); Result result = state.produceResult(); if (result != null) { outputReceiver.get(mainOutputTupleTag).output(KV.of(processingState.getKey(), result)); processingState.resultProduced(); } processingState.processedBufferedEvent(eventSequence); // Remove this record also endClearRange = Instant.ofEpochMilli(eventSequence + 1); } // Temporarily disabled due to https://github.com/apache/beam/pull/28171 // bufferedEventsState.clearRange(startRange, endClearRange); // TODO: Draining events is a temporary workaround related to https://github.com/apache/beam/issues/28370 // It can be removed once https://github.com/apache/beam/pull/28371 is available in a regular release while (bufferedEventsIterator.hasNext()) { // Read and discard all events bufferedEventsIterator.next(); } diagnostics.setQueriedBufferedEvents( QueriedBufferedEvents.create(startRange, endRange, firstEventRead));
diagnostics.setClearedBufferedEvents(ClearedBufferedEvents.create(startRange, endClearRange));
1
2023-11-15 21:26:06+00:00
8k
Hikaito/Fox-Engine
src/system/project/treeElements/ProjectFile.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static LayerManager layerManager;\n private static UndoRedoStack undoRedoStack;\n private static ProjectManager projectManager;\n\n // function to launch, control, and represent program window\n public static void main(String[] args){\n\n // load user settings\n userSetting = UserSetting.get();\n if (!userSetting.pathDefaultProject.equals(\"\")) FileOperations.generateDirectories(); // refresh directories if a project was selected\n\n // load project\n projectManager = new ProjectManager(); // generate manager\n // if no project, then initialize null\n if(userSetting.pathDefaultProject.equals(\"\")) projectManager.initializeEmpty();\n else projectManager.loadProject(getProjectPath()); // load project\n\n // initialize project\n layerManager = new LayerManager();\n layerManager.setProjectID(projectManager.getUUID());\n layerManager.setProjectTitle(projectManager.getTitle());\n\n // initialize undo/redo stack\n undoRedoStack = new UndoRedoStack(userSetting.undoMax);\n\n //initialize frame\n try {\n window = new MainWindow();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n //endregion\n //region utility functions---------------------------------------------------\n\n // Version numbers\n private static VersionNumber programVersionNumber = new VersionNumber(\"1.0.0\");\n public static VersionNumber getProgramVersion(){return programVersionNumber;}\n\n // function for log output\n private static final PrintStream logStreamOut = System.out; // stream for log outputs\n public static void log(String input){\n logStreamOut.println(input);\n }\n\n // window title\n public static String getWindowTitle(){return \"Fox Engine\";}\n\n // GSON builder\n private static final Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag\n .setPrettyPrinting() // creates a pretty version of the output\n .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter\n .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer\n .create();\n\n //endregion\n //region MainWindow operations --------------------------------------------\n\n // composite function: re-render both canvas and editors\n public static void redrawAllRegions(){\n redrawCanvas();\n redrawLayerEditor();\n }\n\n // composite function: re-render editor panes\n public static void redrawLayerEditor(){\n layerManager.rebuildLayerTree();\n layerManager.rebuildEditorPanel();\n window.repaintLayerEditor(); //clears lingering removed elements from underlying rectangles\n }\n\n // vanilla functions\n public static void redrawCanvas(){\n window.redrawCanvas();\n } // re-render the canvas image from layer tree\n public static void redrawMenuBar(){\n window.regenMenuBar();\n } // rerender menu bar\n public static void zoomInCanvas(){ window.zoomInCanvas(); }\n public static void zoomOutCanvas(){ window.zoomOutCanvas();}\n\n //endregion\n //region ProjectManager -----------------------------\n\n // loads the image associated with a filecode\n public static String getProjectID(){return projectManager.getUUID();}\n public static ProjectFile getImageFile(long fileCode){ return projectManager.getFile(fileCode);}\n public static BufferedImage getImage(long fileCode){\n //get file\n ProjectFile file = projectManager.getFile(fileCode);\n if (file == null) return null;\n String path = projectManager.getAbsolutePath(file); // get image path\n try {\n return ImageIO.read(new File(path));\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n public static void saveProject() {projectManager.saveFile();}\n public static void loadProject(){projectManager.loadProject();}\n public static void editProject(){projectManager.openEditor();}\n public static void selectFileFromProject(Layer layer){projectManager.openSelector(layer);}\n public static void selectIntersectClippingFile(Folder folder){projectManager.openSelector(folder);}\n public static JMenu getProjectMenu(){\n return projectManager.getMenu();\n }\n\n // endregion\n // region SelectionManger [via LayerManager] -----------------------\n\n public static void addSelection(TreeUnit obj){layerManager.addSelection(obj);}\n public static void removeSelection(TreeUnit obj){layerManager.removeSelection(obj);}\n public static void clearSelection(){layerManager.clearSelection();}\n public static TreeUnit peekSelectionTop(){return layerManager.peekSelectionTop();}\n public static SelectionManager.selectionPriority getSelectionStatus(){return layerManager.getSelectionStatus();}\n public static SelectionManager.selectionPriority checkSelection(TreeUnit obj){return layerManager.checkSelection(obj);}\n public static Color selectionColor(TreeUnit unit){return layerManager.selectionColor(unit);}\n\n // endregion\n // region LayerManager operations ---------------------------------\n\n //generate a save file for the project manager\n public static boolean generateManagerFile(String path){\n // derive json\n String json = gson.toJson(layerManager);\n\n // write json to file\n try {\n FileWriter out = new FileWriter(path, false);\n out.write(json);\n out.close();\n Program.log(\"LayerManager Save File '\" + path + \"' successfully written.\");\n } catch (IOException e) {\n //e.printStackTrace(); fixme\n Program.log(\"LayerManager Save File '\" + path + \"' could not be written.\");\n return false;\n }\n\n return true;\n }\n\n // open a save and generate a manager to hold it; does not assign a manager\n public static LayerManager loadManagerFile(String path){\n\n // return control object loaded from file if possible\n try {\n String json = new String(Files.readAllBytes(Paths.get(path)));\n return gson.fromJson(json, LayerManager.class);\n }\n\n // return null if no object could be loaded\n catch (IOException e) {\n Program.log(\"LayerManager Save File '\" + path + \"' could not be read.\");\n return null;\n }\n }\n\n // open a save file and load it as the layer manager\n public static void loadFileAsManager(String path){\n LayerManager temp = loadManagerFile(path); // load file\n if (temp == null) return; // reject failed loads\n\n //if successful, perform program transition\n layerManager.replaceManager(temp);\n redrawAllRegions();\n Program.log(\"LayerManager Save File '\" + path + \"' loaded as layer manager.\");\n }\n\n // open a save file and merge it into the existing tree\n public static void mergeFileAsManager(String path){\n LayerManager temp = loadManagerFile(path); // load file\n if (temp == null) return; // reject failed loads\n\n //if successful, perform program transition\n layerManager.addManager(temp);\n redrawAllRegions();\n Program.log(\"LayerManager Save File '\" + path + \"' loaded as layer manager.\");\n }\n\n // vanilla functions\n public static void clearFile(){layerManager.clear();}\n public static void moveLayer(TreeUnit unit, LayerManager.direction dir){layerManager.moveLayer(unit, dir);}\n public static void addFolder(){layerManager.addFolder();}\n public static void addLayer(){layerManager.addLayer();}\n public static void addLayer(long code, boolean useColor, Color color){layerManager.addLayer(code, useColor, color);}\n public static void duplicateTreeUnit(TreeUnit unit){layerManager.duplicate(unit);}\n public static void deleteTreeUnit(TreeUnit unit, Boolean bool){layerManager.delete(unit, bool);}\n public static void markImageForRender(TreeUnit unit){layerManager.markImageForRender(unit);}\n public static void markParentForRender(TreeUnit unit){layerManager.markParentForRender(unit);}\n public static BufferedImage getCanvasImage(){return layerManager.stackImage();}\n public static JPanel getLayerTreePanel(){return layerManager.getLayerTreePanel();}\n public static JPanel getLayerEditPanel(){return layerManager.getLayerEditorPanel();}\n\n //endregion\n //region file operations ---------------------------------------------------\n\n // file editing\n public static void loadTemplate(){ FileOperations.loadTemplate();}\n public static void addTemplate(){ FileOperations.addTemplate();}\n public static void saveTemplate(){ FileOperations.saveTemplate();}\n public static void loadImage(){ FileOperations.loadImage();}\n public static void saveFile(){ FileOperations.saveFile();}\n public static void exportImage(){ FileOperations.exportDialogue();}\n public static void newFile(){ FileOperations.newFile(true);}\n public static void newFileNoWarning(){ FileOperations.newFile(false);}\n\n // endregion\n // region undo/redo ---------------------------------------------------\n\n public static void addUndo(Receipt task){\n undoRedoStack.add(task);\n }\n public static void redo(){\n undoRedoStack.redo();\n }\n public static void undo(){\n undoRedoStack.undo();\n }\n\n // endregion\n // region UserSetting object accessors and mutators ---------------------------------------------------\n\n public static int getScrollMouseAcceleration(){return userSetting.canvasMouseAcceleration;}\n public static double getCanvasScaleFactor(){return userSetting.canvasScaleFactor;}\n public static int getCanvasSliderMin(){return userSetting.canvasSliderMin;}\n public static int getCanvasSliderMax(){return userSetting.canvasSliderMax;}\n public static int getCanvasSliderNeutral(){return userSetting.canvasSliderNeutral;}\n public static int getDefaultCanvasWidth(){return userSetting.defaultCanvasWidth;}\n public static int getDefaultCanvasHeight(){return userSetting.defaultCanvasHeight;}\n public static int getDefaultWindowWidth(){return userSetting.defaultWindowWidth;}\n public static int getDefaultWindowHeight(){return userSetting.defaultWindowHeight;}\n public static int getUndoMax(){return userSetting.undoMax;}\n public static Color getPrimarySelectionColor(){return userSetting.colorPrimarySelection;}\n public static Color getSecondarySelectionColor(){return userSetting.colorSecondarySelection;}\n public static Color getManySelectionColor(){return userSetting.colorManySelection;}\n public static String getDefaultRenderableTitle(){return userSetting.defaultRenderableTitle;}\n public static long getDefaultFileCode() {return userSetting.defaultFileCode;}\n public static String getSaveFileExtension(){return userSetting.fileExtensionSave;}\n public static String getImageFileExtension(){return userSetting.fileExtensionRender;}\n public static String getImageExportFormat(){return userSetting.imageRenderFormat;}\n public static String getAutosavePath(String file){\n //path format: \"file.txt_AUTO.txt\" in the autosave folder\n return Paths.get( Program.getSaveFolderPath(), file + userSetting.filenameExtensionAutosave + userSetting.fileExtensionSave).toString();\n }\n public static String getFileExtensionLoadImage(){return userSetting.fileExtensionLoadImage;}\n public static String getProjectFile(){return userSetting.projectFileName;}\n public static String getProjectPath(){ return userSetting.pathDefaultProject;}\n public static void setProjectPath(String path){\n userSetting.pathDefaultProject = path; // set variable\n userSetting.exportJson(); // export object\n FileOperations.generateDirectories(); // refresh directories\n }\n public static String getSaveFolder(){return userSetting.pathExportSaveFolder;}\n public static String getSaveFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathExportSaveFolder).toString();}\n public static String getTemplateFolder(){return userSetting.pathSourceTemplateFolder;}\n public static String getTemplateFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathSourceTemplateFolder).toString();}\n public static String getRenderFolder(){return userSetting.pathExportImageFolder;}\n public static String getExportFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathExportImageFolder).toString();}\n\n // endregion\n}" }, { "identifier": "FileOperations", "path": "src/system/backbone/FileOperations.java", "snippet": "public class FileOperations {\n\n // region file editing functions--------------------------------------------\n // fixme add redo and undo as appropriate\n\n //removes extension from file name\n public static String stripExtension(String path, String extension){\n if (path.length() < extension.length()) return path;\n return path.substring(0, path.length() - extension.length());\n }\n\n // extract file name from directory\n public static String stripDirectory(String path){\n File file = new File(path);\n return file.getName();\n }\n\n public static boolean validExtension(String path, String extension){\n // get length of extension\n int len = extension.length();\n\n // if file name is too short, invalid\n if (path.length() < len) return false;\n\n // otherwise validate for file ending\n String lastLen = path.substring(path.length() - len); // get the last characters of the extension\n return lastLen.toLowerCase().equals(extension.toLowerCase());\n //returns true if valid ending found and false otherwise\n }\n\n // file extension validation\n public static String validateExtension(String file, String extension){\n // get length of extension\n int len = extension.length();\n\n // if file name is too short, extend\n if (file.length() < len) return file+extension;\n\n // otherwise validate for file ending\n String lastLen = file.substring(file.length() - len); // get the last characters of the extension\n if (! lastLen.toLowerCase().equals(extension.toLowerCase())) return file+extension;\n\n // if extension found and valid, return given file name\n return file;\n }\n\n //get relative path for a file with respect to an absolute path\n public static Path trimDirectory(String directory, String path){\n Path absolute = Paths.get(path); //get absolute path\n Path relative = Paths.get(directory); //get directory\n return relative.relativize(absolute); // return relative path\n }\n\n // file selection dialogue\n public static String selectFile(String basepath){\n //open file selection dialogue\n JFileChooser selectFile = new JFileChooser(basepath);\n \n // if user approves load operation, return file\n if(selectFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) return selectFile.getSelectedFile().getAbsolutePath();\n else return null;\n }\n\n // folder selection dialogue\n public static String selectFolder(String basepath){\n //open file selection dialogue\n JFileChooser selectFile = new JFileChooser(basepath);\n selectFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\n // if user approves load operation, return file\n if(selectFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) return selectFile.getSelectedFile().getAbsolutePath();\n else return null;\n }\n\n // replace current file with template file\n public static void loadTemplate(){\n // get user path\n String path = selectFile(Program.getTemplateFolderPath());\n\n // if valid file selected\n if(path != null){\n //send template to LayerManager to load file\n Program.loadFileAsManager(path);\n\n // log action\n Program.log(\"File \" + path + \" loaded as template.\");\n }\n }\n\n // add selected template to current file\n public static void addTemplate(){\n // get user path\n String path = selectFile(Program.getTemplateFolderPath());\n\n // if valid file selected\n if(path != null){\n //send template to LayerManager to load file\n Program.mergeFileAsManager(path);\n\n // log action\n Program.log(\"File \" + path + \" added to current file as template.\");\n }\n }\n\n // save file as new template\n public static void saveTemplate(){\n // get user path\n String path = selectFile(Program.getTemplateFolderPath());\n\n // if valid file selected\n if(path != null){\n // validate for file ending\n path = validateExtension(path, Program.getSaveFileExtension());\n\n // log action\n Program.log(\"File \" + path + \" attempt writing as new template file.\");\n\n //write to file: write layer manager state to a file\n Program.generateManagerFile(path);\n\n // log action\n Program.log(\"File \" + path + \" written as new template file.\");\n }\n }\n\n // load file\n public static void loadImage(){\n // get user path\n String path = selectFile(Program.getSaveFolderPath());\n\n // if valid file selected\n if(path != null){\n //send template to LayerManager to load file\n Program.loadFileAsManager(path);\n\n // log action\n Program.log(\"File \" + path + \" loaded as file.\");\n }\n }\n\n // save file\n public static void saveFile(){\n // get user path\n String path = selectFile(Program.getSaveFolderPath());\n\n // if valid file selected\n if(path != null){\n // validate for file ending\n path = validateExtension(path, Program.getSaveFileExtension());\n\n // log action\n Program.log(\"File \" + path + \" attempt writing as save file.\");\n\n //write to file: write layer manager state to a file\n Program.generateManagerFile(path);\n\n // log action\n Program.log(\"File \" + path + \" written as save file.\");\n }\n }\n\n //method for exporting a final image; autosaves a copy as a regular document as well\n public static void exportDialogue(){\n Program.redrawCanvas(); //reset canvas fixme\n\n // get user path\n String path = selectFile(Program.getExportFolderPath());\n\n // if valid file selected\n if(path != null){\n // validate for file ending\n path = validateExtension(path, Program.getImageFileExtension());\n\n //if image can be saved, save the image. Otherwise report an error\n try {\n //write image to selected location\n if (ImageIO.write(Program.getCanvasImage(), Program.getImageExportFormat(), new File(path))){\n // log action\n Program.log(\"Image saved at \" + path);\n\n //if write was successful, autosave a log as well\n String autosavePath = FileOperations.stripDirectory(path); // isolate file name\n autosavePath = FileOperations.stripExtension(autosavePath, Program.getImageFileExtension()); // isolate file extension\n autosavePath = Program.getAutosavePath(autosavePath); // add folder and extension\n\n //write to file: write layer manager state to a file\n Program.generateManagerFile(autosavePath);\n\n // log action\n Program.log(\"Autosave saved at \" + autosavePath);\n }\n //if file was not opened, report error\n else{\n // log action\n Program.log(\"Image \" + path + \" failed to save.\");\n }\n //if file had catastrophic failure, report error\n } catch (IOException ioException) {\n // log action\n Program.log(\"Image \" + path + \" failed to save; Exception thrown. (may have also been failure of autosave of template)\");\n }\n }\n }\n\n // generate new file\n public static void newFile(boolean doWarning){\n //signal delete canvas; delete file with warning if warning given\n if (doWarning) WarningWindow.warningWindow(\"This will delete the file. Proceed?\", new newFileWarning());\n else new newFileWarning().enact();\n }\n public static class newFileWarning implements EventE {\n @Override\n public void enact() {\n //signal delete canvas\n Program.clearFile();\n\n // log action\n Program.log(\"File cleared (layer tree erased).\");\n }\n }\n // endregion\n //region folder initialization---------\n //region initialization functions\n //function that generates path folders if they do not exist\n public static void generateDirectories(){\n File file;\n //code tests and generates a directory if necessary for each folder path\n\n file = new File(Program.getProjectPath()); //get an absolute path file\n if(!file.isDirectory()){\n file.mkdir(); //if file is not a directory, make the directory\n Program.log(\"Directory generated at '\" + file + \"'\");\n }\n\n file = new File(Program.getTemplateFolderPath()); //get an absolute path file\n if(!file.isDirectory()){\n file.mkdir(); //if file is not a directory, make the directory\n Program.log(\"Directory generated at '\" + file + \"'\");\n }\n\n file = new File(Program.getExportFolderPath()); //get an absolute path file\n if(!file.isDirectory()){\n file.mkdir(); //if file is not a directory, make the directory\n Program.log(\"Directory generated at '\" + file + \"'\");\n }\n\n file = new File(Program.getSaveFolderPath()); //get an absolute path file\n if(!file.isDirectory()){\n file.mkdir(); //if file is not a directory, make the directory\n Program.log(\"Directory generated at '\" + file + \"'\");\n }\n }\n //endregion\n}" }, { "identifier": "WarningWindow", "path": "src/system/gui/WarningWindow.java", "snippet": "public class WarningWindow {\n //warning window that invokes an action on acceptance\n public static void warningWindow(String text, EventE event){\n JFrame frame = new JFrame();\n\n //overall window\n JFrame jFrame = new JFrame(\"Warning\"); //initialize window title\n jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited\n jFrame.setSize(CoreGlobal.WARNING_WINDOW_WIDTH,CoreGlobal.WARNING_WINDOW_HEIGHT); //initialize size\n jFrame.setLocationRelativeTo(null); //center window\n\n // main region\n JPanel region = new JPanel();\n region.setLayout(new BoxLayout(region,BoxLayout.Y_AXIS)); //stack items vertically\n jFrame.add(region);\n\n // text region\n region.add(new JLabel(text));\n\n // buttons region\n JPanel buttons = new JPanel();\n buttons.setLayout(new FlowLayout()); // host items horizontally\n region.add(buttons);\n\n //cancel button\n JButton cancelButton = new JButton(\"Cancel\");\n //on selection, toggle using original color\n cancelButton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n jFrame.dispose();\n }\n });\n buttons.add(cancelButton);\n\n //accept button\n //cancel button\n JButton acceptButton = new JButton(\"Accept\");\n //on selection, toggle using original color\n acceptButton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n //set values\n if (event != null) event.enact();\n jFrame.dispose();\n }\n });\n buttons.add(acceptButton);\n\n jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization)\n\n //[it should probably lock other windows and also spawn in the middle]\n }\n\n //warning window that pops up but doesn't do anything\n public static void warningWindow(String text){\n JFrame frame = new JFrame();\n\n //overall window\n JFrame jFrame = new JFrame(\"Warning\"); //initialize window title\n jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited\n jFrame.setSize(CoreGlobal.WARNING_WINDOW_WIDTH,CoreGlobal.WARNING_WINDOW_HEIGHT); //initialize size\n jFrame.setLocationRelativeTo(null); //center window\n\n // main region\n JPanel region = new JPanel();\n region.setLayout(new BoxLayout(region,BoxLayout.Y_AXIS)); //stack items vertically\n jFrame.add(region);\n\n // text region\n region.add(new JLabel(text));\n\n // buttons region\n JPanel buttons = new JPanel();\n buttons.setLayout(new FlowLayout()); // host items horizontally\n region.add(buttons);\n\n //accept button\n //cancel button\n JButton acceptButton = new JButton(\"Accept\");\n //on selection, toggle using original color\n acceptButton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n //set values\n jFrame.dispose();\n }\n });\n buttons.add(acceptButton);\n\n jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization)\n\n //[it should probably lock other windows and also spawn in the middle]\n }\n}" } ]
import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import system.Program; import system.backbone.FileOperations; import system.gui.WarningWindow; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage;
5,969
package system.project.treeElements; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> { // constructor public ProjectFile(String title, long id){ super("file", id); //super this.title = title; } // longer constructor public ProjectFile(String path, String title, long id){ super("file", id); //super this.path = path; this.title = title; } //path for file @Expose @SerializedName(value = "filepath") protected String path = ""; public String getPath(){return path;} public void setPath(String path){this.path = path;} public void setNewPath(String directory, String path){ // reject if directory doesn't match if(!(directory.equals(path.substring(0, directory.length())))){
package system.project.treeElements; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> { // constructor public ProjectFile(String title, long id){ super("file", id); //super this.title = title; } // longer constructor public ProjectFile(String path, String title, long id){ super("file", id); //super this.path = path; this.title = title; } //path for file @Expose @SerializedName(value = "filepath") protected String path = ""; public String getPath(){return path;} public void setPath(String path){this.path = path;} public void setNewPath(String directory, String path){ // reject if directory doesn't match if(!(directory.equals(path.substring(0, directory.length())))){
WarningWindow.warningWindow("File rejected; must be in root folder.");
2
2023-11-12 21:12:21+00:00
8k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/dashboard/DashboardFragment.java
[ { "identifier": "Repository", "path": "app/src/main/java/gr/ihu/geoapp/managers/Repository.java", "snippet": "public class Repository {\n private static final String BASE_URL = \"http://192.168.1.6/geoapp/\";\n private static Repository instance;\n\n private Repository() {\n }\n\n public static Repository getInstance() {\n if (instance == null) {\n synchronized (Repository.class) {\n if (instance == null) {\n instance = new Repository();\n }\n }\n }\n return instance;\n }\n\n /**\n * Performs a login operation.\n * Sends a POST request to the server with the user's email and password.\n * The server's response is passed to the provided callback.\n *\n * @param email the user's email address\n * @param password the user's password\n * @param callback the callback to handle the server's response\n */\n public void login(String email, String password, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"email\", email);\n requestData.put(\"password\", password);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"login.php\", requestData, callback);\n }\n\n /**\n * Performs a registration operation.\n * Sends a POST request to the server with the user's details.\n * The server's response is passed to the provided callback.\n *\n * @param full_name the user's full name\n * @param email the user's email address\n * @param password the user's password\n * @param birthdate the user's birthdate\n * @param job the user's job\n * @param diploma the user's diploma\n * @param callback the callback to handle the server's response\n */\n public void register(String full_name, String email, String password, String birthdate, String job,\n String diploma, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"full_name\", full_name);\n requestData.put(\"email\", email);\n requestData.put(\"password\", password);\n requestData.put(\"birthdate\", birthdate);\n requestData.put(\"job\", job);\n requestData.put(\"diploma\", diploma);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"register.php\", requestData, callback);\n\n }\n\n /**\n * Performs a logout operation.\n * Sends a POST request to the server with the user's email and API key.\n * The server's response is passed to the provided callback.\n *\n * @param email the user's email address\n * @param apiKey the user's API key\n * @param callback the callback to handle the server's response\n */\n public void logout(String email, String apiKey, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"email\", email);\n requestData.put(\"apiKey\", apiKey);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"api.php\", requestData, callback);\n\n }\n\n /**\n * Performs an API request to the server.\n * Sends a POST request to the specified endpoint with the provided data.\n * The server's response is passed to the provided callback.\n *\n * @param endpoint the endpoint to send the request to\n * @param requestData the data to send in the request\n * @param callback the callback to handle the server's response\n *\n */\n\n @SuppressLint(\"StaticFieldLeak\")\n public void performAPIRequest(final String endpoint, final JSONObject requestData, final RepositoryCallback callback) {\n new AsyncTask<Void, Void, String>() {\n /**\n * Background task to execute the API request.\n *\n * @param voids not used\n * @return a JSON string representing the server's response\n */\n @Override\n protected String doInBackground(Void... voids) {\n HttpURLConnection connection = null;\n StringBuilder response = new StringBuilder();\n\n try {\n URL url = new URL(BASE_URL + endpoint);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"POST\");\n connection.setDoOutput(true);\n\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n String postData = encodeDataAsFormUrlEncoded(requestData);\n\n OutputStream outputStream = connection.getOutputStream();\n outputStream.write(postData.getBytes(\"UTF-8\"));\n outputStream.close();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n reader.close();\n\n } catch (IOException | JSONException e) {\n e.printStackTrace();\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n\n return response.toString();\n }\n /**\n * Callback method called on the main thread after the completion of the API request.\n *\n * @param response the server's response\n */\n @Override\n protected void onPostExecute(String response) {\n super.onPostExecute(response);\n Log.d(\"response\",response);\n\n try {\n JSONObject jsonResponse = new JSONObject(response);\n\n if (jsonResponse.has(\"status\")) {\n String status = jsonResponse.getString(\"status\");\n if (status.equals(\"success\")) {\n callback.onSuccess(jsonResponse);\n } else {\n callback.onError(jsonResponse.getString(\"status\") + jsonResponse.getString(\"message\"));\n }\n } else {\n callback.onError(\"Invalid response from server\");\n }\n } catch (JSONException e) {\n e.printStackTrace();\n callback.onError(\"Error parsing JSON response\");\n }\n }\n /**\n * Helper method to encode data as form-urlencoded format.\n *\n * @param data the data to be encoded\n * @return a string representing the encoded data\n * @throws UnsupportedEncodingException if the encoding is not supported\n * @throws JSONException if there is an issue with JSON processing\n */\n private String encodeDataAsFormUrlEncoded(JSONObject data) throws UnsupportedEncodingException, JSONException {\n StringBuilder result = new StringBuilder();\n boolean first = true;\n Iterator<String> keys = data.keys();\n\n while (keys.hasNext()) {\n String key = keys.next();\n String value = data.getString(key);\n\n if (first) {\n first = false;\n } else {\n result.append(\"&\");\n }\n\n result.append(URLEncoder.encode(key, \"UTF-8\"));\n result.append(\"=\");\n result.append(URLEncoder.encode(value, \"UTF-8\"));\n }\n return result.toString();\n }\n\n\n }.execute();\n }\n /**\n * An interface for handling the callbacks from the API requests.\n */\n public interface RepositoryCallback {\n /**\n * Called when the API request is successful.\n *\n * @param response the server's response\n */\n void onSuccess(JSONObject response);\n /**\n * Called when the API request encounters an error.\n *\n * @param error the error message\n */\n void onError(String error);\n }\n}" }, { "identifier": "RegularUser", "path": "app/src/main/java/gr/ihu/geoapp/models/users/RegularUser.java", "snippet": "public class RegularUser{\n private String user_id;\n private String full_name;\n private String password;\n private String email;\n private String birthdate;\n private String job;\n private String diploma;\n private String api_key;\n private List<Image> imageList;\n\n private static RegularUser instance;\n\n private RegularUser() {\n this.user_id = \"N/A\";\n this.full_name = \"N/A\";\n this.email = \"N/A\";\n this.birthdate = \"N/A\";\n this.job = \"N/A\";\n this.diploma = \"N/A\";\n this.imageList = new ArrayList<>();\n }\n\n public static RegularUser getInstance() {\n if (instance == null) {\n instance = new RegularUser();\n }\n return instance;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUserId() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param userId the user's ID\n */\n public void setUserId(String userId) {\n this.user_id = userId;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFullName() {\n return full_name;\n }\n\n /**\n * Sets the full name of the user.\n *\n * @param fullName the user's full name\n */\n public void setFullName(String fullName) {\n this.full_name = fullName;\n }\n\n /**\n * Gets the email of the user.\n *\n * @return the user's email\n */\n public String getEmail() {\n return email;\n }\n\n /**\n * Sets the email of the user.\n *\n * @param email the user's email\n */\n public void setEmail(String email) {\n this.email = email;\n }\n\n /**\n * Gets the birth date of the user.\n *\n * @return the user's birth date\n */\n public String getBirthdate() {\n return birthdate;\n }\n\n /**\n * Sets the birth date of the user.\n *\n * @param birthdate the user's birth date\n */\n public void setBirthdate(String birthdate) {\n this.birthdate = birthdate;\n }\n\n /**\n * Gets the job of the user.\n *\n * @return the user's job\n */\n public String getJob() {\n return job;\n }\n\n /**\n * Sets the job of the user.\n *\n * @param job the user's job\n */\n public void setJob(String job) {\n this.job = job;\n }\n\n /**\n * Gets the diploma of the user.\n *\n * @return the user's diploma\n */\n public String getDiploma() {\n return diploma;\n }\n\n /**\n * Sets the diploma of the user.\n *\n * @param diploma the user's diploma\n */\n public void setDiploma(String diploma) {\n this.diploma = diploma;\n }\n\n /**\n * Sets the singleton instance of the RegularUser class.\n *\n * @param instance the instance to set\n */\n public static void setInstance(RegularUser instance) {\n RegularUser.instance = instance;\n }\n\n /**\n * Gets the password of the user.\n *\n * @return the user's password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Sets the password of the user.\n *\n * @param password the user's password\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Gets the API key of the user.\n *\n * @return the user's API key\n */\n public String getApi_key() {\n return api_key;\n }\n\n /**\n * Sets the API key of the user.\n *\n * @param api_key the user's API key\n */\n public void setApi_key(String api_key) {\n this.api_key = api_key;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUser_id() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param user_id the user's ID\n */\n public void setUser_id(String user_id) {\n this.user_id = user_id;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFull_name() {\n return full_name;\n }\n /**\n * Sets the full name of the user.\n *\n * @param full_name the user's full name\n */\n public void setFull_name(String full_name) {\n this.full_name = full_name;\n }\n\n /**\n * Gets the list of images associated with the user.\n *\n * @return the list of images\n */\n public List<Image> getImageList() {\n return imageList;\n }\n\n /**\n * Sets the list of images associated with the user.\n *\n * @param imageList the list of images\n */\n public void setImageList(List<Image> imageList) {\n this.imageList = imageList;\n }\n}" }, { "identifier": "PhotoBinActivity", "path": "app/src/main/java/gr/ihu/geoapp/ui/dashboard/PhotoBinActivity/PhotoBinActivity.java", "snippet": "public class PhotoBinActivity extends AppCompatActivity {\n private GridView gridView;\n private ArrayList<String> imagePaths;\n\n /**\n * Initializes the activity.\n * Sets the content view to the photo bin fragment layout.\n * Fetches the images taken today and sets them in the grid view.\n *\n * @param savedInstanceState the state of the activity\n */\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.photo_bin_fragment_layout);\n\n gridView = findViewById(R.id.gridView);\n imagePaths = getTodayImages();\n\n ImageAdapter imageAdapter = new ImageAdapter();\n gridView.setAdapter(imageAdapter);\n }\n\n /**\n * Fetches the images taken today from the external storage of the device.\n *\n * @return a list of paths to the images taken today\n */\n private ArrayList<String> getTodayImages() {\n ArrayList<String> paths = new ArrayList<>();\n Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;\n String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN};\n Cursor cursor = getContentResolver().query(uri, projection, null, null, MediaStore.Images.Media.DATE_TAKEN + \" DESC\");\n\n if (cursor != null) {\n while (cursor.moveToNext()) {\n String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));\n long dateTaken = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN));\n\n if (isToday(dateTaken)) {\n paths.add(imagePath);\n }\n }\n cursor.close();\n }\n\n return paths;\n }\n\n /**\n * Checks if the given date corresponds to today's date.\n *\n * @param dateTaken the date to check\n * @return true if the date corresponds to today, false otherwise\n */\n private boolean isToday(long dateTaken) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMdd\", Locale.getDefault());\n String todayDate = sdf.format(new Date());\n String imageDate = sdf.format(new Date(dateTaken));\n\n return todayDate.equals(imageDate);\n }\n\n /**\n * An inner class representing the adapter for the grid view.\n * It fetches the images from the image paths and sets them in the grid view.\n * When an image is clicked, it opens the image.\n */\n private class ImageAdapter extends BaseAdapter {\n\n /**\n * Returns the count of images.\n *\n * @return the count of images\n */\n @Override\n public int getCount() {\n return imagePaths.size();\n }\n\n /**\n * Returns the item at the specified position.\n *\n * @param position the position of the item\n * @return the item at the specified position\n */\n @Override\n public Object getItem(int position) {\n return imagePaths.get(position);\n }\n\n /**\n * Returns the id of the item at the specified position.\n *\n * @param position the position of the item\n * @return the id of the item at the specified position\n */\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n /**\n * Returns the view for the item at the specified position.\n * Sets the image for the view and handles click events.\n *\n * @param position the position of the item\n * @param convertView the view to reuse\n * @param parent the parent view group\n * @return the view for the item at the specified position\n */\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ImageView imageView;\n if (convertView == null) {\n imageView = new ImageView(PhotoBinActivity.this);\n imageView.setLayoutParams(new GridView.LayoutParams(300, 300));\n imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);\n imageView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClick(position);\n }\n });\n } else {\n imageView = (ImageView) convertView;\n }\n\n Glide.with(PhotoBinActivity.this)\n .load(imagePaths.get(position))\n .into(imageView);\n\n return imageView;\n }\n\n /**\n * Handles the click event for an item.\n * Opens the selected image.\n *\n * @param position the position of the clicked item\n */\n private void onItemClick(int position) {\n String selectedImagePath = imagePaths.get(position);\n\n Intent resultIntent = new Intent();\n resultIntent.setData(Uri.parse(selectedImagePath));\n setResult(Activity.RESULT_OK, resultIntent);\n\n finish();\n\n }\n\n\n\n\n\n }\n}" }, { "identifier": "RegisterActivity", "path": "app/src/main/java/gr/ihu/geoapp/ui/signup/RegisterActivity.java", "snippet": "public class RegisterActivity extends AppCompatActivity {\n\n private EditText fullNameEditText;\n private EditText emailEditText;\n private EditText passwordEditText;\n private EditText passwordConfirmEditText;\n private EditText birthDateEditText;\n private EditText professionEditText;\n private EditText diplomaEditText;\n ProgressBar progressBar;\n private ActivityRegisterBinding binding;\n private RegisterViewModel registerViewModel;\n\n /**\n * Initializes the activity.\n * Sets up the click listeners for the register and sign in buttons.\n *\n * @param savedInstanceState the saved instance state\n */\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n registerViewModel =\n new ViewModelProvider(this).get(RegisterViewModel.class);\n\n binding = ActivityRegisterBinding.inflate(getLayoutInflater());\n View view = binding.getRoot();\n setContentView(view);\n\n fullNameEditText = binding.fullNameEditText;\n emailEditText = binding.emailEditText;\n passwordEditText = binding.passwordEditText;\n progressBar = binding.progressBar;\n passwordConfirmEditText = binding.conPasswordEditText;\n birthDateEditText = binding.birthDateEditText;\n professionEditText = binding.professionEditText;\n diplomaEditText = binding.diplomaEditText;\n\n Button registerButton = binding.buttonRegister;\n registerButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n progressBar.setVisibility(View.VISIBLE);\n\n if (Validator.validateName(fullNameEditText) && Validator.validateEmail(emailEditText) && Validator.validatePassword(passwordEditText)\n && Validator.validateBirth(birthDateEditText) && Validator.validateProfession(professionEditText) && Validator.validateDiploma(diplomaEditText)) {\n\n String newUserEmail = emailEditText.getText().toString().trim();\n String newUserPassword = passwordEditText.getText().toString().trim();\n String newUserFullName = fullNameEditText.getText().toString().trim();\n String newUserBirthDate = birthDateEditText.getText().toString().trim();\n String newUserProfession = professionEditText.getText().toString().trim();\n String newUserDiploma = diplomaEditText.getText().toString().trim();\n Log.d(\"rest\",newUserEmail + newUserPassword + newUserFullName + newUserBirthDate +newUserProfession +newUserDiploma);\n registerViewModel.register(newUserFullName,newUserEmail,newUserPassword,newUserBirthDate,newUserProfession,newUserDiploma);\n registerViewModel.getRegistrationResult().observe(RegisterActivity.this, new Observer<Boolean>() {\n @Override\n public void onChanged(Boolean success) {\n if (success) {\n showToast(\"Successful registration\");\n navigateToSignInActivity();\n }else{\n showToast(\"Something went wrong. Try again in a moment\");\n }\n }\n });\n\n //navigateToSignInActivity();\n } else {\n Toast.makeText(getApplicationContext(),\"Check for errors\",Toast.LENGTH_SHORT).show();\n progressBar.setVisibility(View.GONE);\n\n }\n\n }\n });\n\n Button signInButton = binding.buttonSignIn;\n signInButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n navigateToSignInActivity();\n }\n });\n }\n\n /**\n * Navigates to the Sign In Activity.\n */\n private void navigateToSignInActivity(){\n Intent intent = new Intent(getApplicationContext(), SignInActivity.class);\n startActivity(intent);\n finish();\n\n }\n\n /**\n * Displays a toast message.\n *\n * @param message the message to display\n */\n private void showToast(String message) {\n Toast.makeText(this, message, Toast.LENGTH_SHORT).show();\n }\n\n}" } ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.bumptech.glide.Glide; import com.google.android.material.chip.Chip; import com.google.android.material.chip.ChipGroup; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import gr.ihu.geoapp.R; import gr.ihu.geoapp.databinding.FragmentDashboardBinding; import gr.ihu.geoapp.databinding.DataLayoutBinding; import gr.ihu.geoapp.managers.Repository; import gr.ihu.geoapp.models.users.RegularUser; import gr.ihu.geoapp.ui.dashboard.PhotoBinActivity.PhotoBinActivity; import gr.ihu.geoapp.ui.signup.RegisterActivity;
6,701
package gr.ihu.geoapp.ui.dashboard; /** * This class represents the Dashboard Fragment in the application. * It provides functionalities for uploading photos, adding tags, and editing descriptions. * It also sends the uploaded photo along with its metadata to an API server. */ public class DashboardFragment extends Fragment { private FragmentDashboardBinding binding; private DataLayoutBinding dataLayoutBinding; public static final int GALLERY_REQUEST_CODE = 1000; public static final int CAMERA_REQUEST_CODE = 2000; private DashboardViewModel dashboardViewModel; private ChipGroup chipGroup; private String currentDescription = ""; private String currentTitle = ""; private FloatingActionButton fab; private static final int PICK_PHOTO_REQUEST = 1; private Bitmap imageBitmap; private EditText tagEditText; private EditText descrEditText; private List<String> tag_csv = null; private EditText titleEditText; /** * Initializes the view of the fragment. * Sets up the click listeners for the buttons and observes changes in the image path and image bitmap. * * @param inflater the LayoutInflater to inflate the view * @param container the container for the view * @param savedInstanceState the saved instance state * @return the view of the fragment */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class); binding = FragmentDashboardBinding.inflate(inflater,container, false); dataLayoutBinding = binding.include; View root = binding.getRoot(); final ImageView imageView = binding.image; tag_csv = new ArrayList<>(); chipGroup = binding.chipGroup; // chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(ChipGroup group, int checkedId) { // // Chip selectedChip = findViewById(checkedId); // if (selectedChip != null) { // String category = selectedChip.getText().toString(); // } // } // }); Button addButton= binding.addButton; tagEditText= binding.tagEditText; descrEditText = dataLayoutBinding.descrEditText; titleEditText = dataLayoutBinding.titleEditText; Button addDescrBtn = dataLayoutBinding.addDescrBtn; Button saveDescrBtn = dataLayoutBinding.saveDescrBtn; Button editDescrBtn = dataLayoutBinding.editDescrBtn; Button addTitleBtn = dataLayoutBinding.addTitleBtn; Button saveTitleBtn = dataLayoutBinding.saveTitleBtn; Button editTitleBtn = dataLayoutBinding.editTitleBtn; Button sendPhotoBtn = binding.sendPhotoBtn; fab = binding.fab; addTitleBtn.setVisibility(View.GONE); addDescrBtn.setVisibility(View.GONE); saveDescrBtn.setVisibility(View.GONE); editDescrBtn.setVisibility(View.GONE); saveTitleBtn.setVisibility(View.GONE); editTitleBtn.setVisibility(View.GONE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), PhotoBinActivity.class); startActivityForResult(intent, PICK_PHOTO_REQUEST); } }); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String newTag = tagEditText.getText().toString().trim(); if (!newTag.isEmpty()) { Chip newChip = new Chip(getContext()); newChip.setText(newTag); chipGroup.addView(newChip); tag_csv.add(newTag); tagEditText.setText(""); } } }); dashboardViewModel.getImagePath().observe(getViewLifecycleOwner(), imagePath -> { if (imagePath != null && !imagePath.isEmpty()) { Glide.with(requireContext()).load(imagePath).into(imageView); } }); dashboardViewModel.getImageBitmap().observe(getViewLifecycleOwner(), imageBitmap -> { if (imageBitmap != null) { imageView.setImageBitmap(imageBitmap); } }); sendPhotoBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ByteArrayOutputStream byteArrayOutputStream; byteArrayOutputStream = new ByteArrayOutputStream(); if (imageBitmap != null) { imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] bytes = byteArrayOutputStream.toByteArray(); final String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT); String url = "http://192.168.1.2/geoapp/img/photo_profile.php"; RequestQueue queue = Volley.newRequestQueue(getContext()); // request method to post the data to API StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { try { Log.d("response",response); JSONObject jsonResponse = new JSONObject(response); String status = jsonResponse.getString("status"); if (status.equals("success")) { String targetPath = jsonResponse.getString("targetPath"); //user.setPhoto(targetPath); //SharedPrefManager.getInstance(getContext()).setPhoto(targetPath); Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(getContext(), "Fail to get response = " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("image", base64Image);
package gr.ihu.geoapp.ui.dashboard; /** * This class represents the Dashboard Fragment in the application. * It provides functionalities for uploading photos, adding tags, and editing descriptions. * It also sends the uploaded photo along with its metadata to an API server. */ public class DashboardFragment extends Fragment { private FragmentDashboardBinding binding; private DataLayoutBinding dataLayoutBinding; public static final int GALLERY_REQUEST_CODE = 1000; public static final int CAMERA_REQUEST_CODE = 2000; private DashboardViewModel dashboardViewModel; private ChipGroup chipGroup; private String currentDescription = ""; private String currentTitle = ""; private FloatingActionButton fab; private static final int PICK_PHOTO_REQUEST = 1; private Bitmap imageBitmap; private EditText tagEditText; private EditText descrEditText; private List<String> tag_csv = null; private EditText titleEditText; /** * Initializes the view of the fragment. * Sets up the click listeners for the buttons and observes changes in the image path and image bitmap. * * @param inflater the LayoutInflater to inflate the view * @param container the container for the view * @param savedInstanceState the saved instance state * @return the view of the fragment */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class); binding = FragmentDashboardBinding.inflate(inflater,container, false); dataLayoutBinding = binding.include; View root = binding.getRoot(); final ImageView imageView = binding.image; tag_csv = new ArrayList<>(); chipGroup = binding.chipGroup; // chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(ChipGroup group, int checkedId) { // // Chip selectedChip = findViewById(checkedId); // if (selectedChip != null) { // String category = selectedChip.getText().toString(); // } // } // }); Button addButton= binding.addButton; tagEditText= binding.tagEditText; descrEditText = dataLayoutBinding.descrEditText; titleEditText = dataLayoutBinding.titleEditText; Button addDescrBtn = dataLayoutBinding.addDescrBtn; Button saveDescrBtn = dataLayoutBinding.saveDescrBtn; Button editDescrBtn = dataLayoutBinding.editDescrBtn; Button addTitleBtn = dataLayoutBinding.addTitleBtn; Button saveTitleBtn = dataLayoutBinding.saveTitleBtn; Button editTitleBtn = dataLayoutBinding.editTitleBtn; Button sendPhotoBtn = binding.sendPhotoBtn; fab = binding.fab; addTitleBtn.setVisibility(View.GONE); addDescrBtn.setVisibility(View.GONE); saveDescrBtn.setVisibility(View.GONE); editDescrBtn.setVisibility(View.GONE); saveTitleBtn.setVisibility(View.GONE); editTitleBtn.setVisibility(View.GONE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), PhotoBinActivity.class); startActivityForResult(intent, PICK_PHOTO_REQUEST); } }); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String newTag = tagEditText.getText().toString().trim(); if (!newTag.isEmpty()) { Chip newChip = new Chip(getContext()); newChip.setText(newTag); chipGroup.addView(newChip); tag_csv.add(newTag); tagEditText.setText(""); } } }); dashboardViewModel.getImagePath().observe(getViewLifecycleOwner(), imagePath -> { if (imagePath != null && !imagePath.isEmpty()) { Glide.with(requireContext()).load(imagePath).into(imageView); } }); dashboardViewModel.getImageBitmap().observe(getViewLifecycleOwner(), imageBitmap -> { if (imageBitmap != null) { imageView.setImageBitmap(imageBitmap); } }); sendPhotoBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ByteArrayOutputStream byteArrayOutputStream; byteArrayOutputStream = new ByteArrayOutputStream(); if (imageBitmap != null) { imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] bytes = byteArrayOutputStream.toByteArray(); final String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT); String url = "http://192.168.1.2/geoapp/img/photo_profile.php"; RequestQueue queue = Volley.newRequestQueue(getContext()); // request method to post the data to API StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { try { Log.d("response",response); JSONObject jsonResponse = new JSONObject(response); String status = jsonResponse.getString("status"); if (status.equals("success")) { String targetPath = jsonResponse.getString("targetPath"); //user.setPhoto(targetPath); //SharedPrefManager.getInstance(getContext()).setPhoto(targetPath); Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(getContext(), "Fail to get response = " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("image", base64Image);
params.put("user_id", RegularUser.getInstance().getUserId());
1
2023-11-10 17:43:18+00:00
8k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/predictionengine/predictions/rideable/PredictionEngineRideableLava.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keepalive and transactions is that keepalive is async while transactions are sync\n public final Queue<Pair<Short, Long>> transactionsSent = new ConcurrentLinkedQueue<>();\n // Sync this to the netty thread because when spamming transactions, they can get out of order... somehow\n public final ConcurrentList<Short> didWeSendThatTrans = new ConcurrentList<>();\n private final AtomicInteger transactionIDCounter = new AtomicInteger(0);\n public Vector clientVelocity = new Vector();\n public double lastWasClimbing = 0;\n public boolean canSwimHop = false;\n public int riptideSpinAttackTicks = 0;\n public boolean hasGravity = true;\n public boolean playerEntityHasGravity = true;\n public VectorData predictedVelocity = new VectorData(new Vector(), VectorData.VectorType.Normal);\n public Vector actualMovement = new Vector();\n public Vector stuckSpeedMultiplier = new Vector(1, 1, 1);\n public Vector blockSpeedMultiplier = new Vector(1, 1, 1);\n public UncertaintyHandler uncertaintyHandler;\n public double gravity;\n public float friction;\n public double speed;\n public double x;\n public double y;\n public double z;\n public double lastX;\n public double lastY;\n public double lastZ;\n public float xRot;\n public float yRot;\n public float lastXRot;\n public float lastYRot;\n public boolean onGround;\n public boolean lastOnGround;\n public boolean isSneaking;\n public boolean wasSneaking;\n public boolean isCrouching;\n public boolean isSprinting;\n public boolean lastSprinting;\n public AlmostBoolean isUsingItem;\n public boolean isFlying;\n public boolean wasFlying;\n // If a player collides with the ground, their flying will be set false after their movement\n // But we need to know if they were flying DURING the movement\n // Thankfully we can 100% recover from this using some logic in PredictionData\n // If the player touches the ground and was flying, and now isn't flying - the player was flying during movement\n // Or if the player is flying - the player is flying during movement\n public boolean specialFlying;\n public boolean isSwimming;\n public boolean wasSwimming;\n public boolean isClimbing;\n public boolean isGliding;\n public boolean wasGliding;\n public boolean isRiptidePose = false;\n public double fallDistance;\n public SimpleCollisionBox boundingBox;\n public Pose pose = Pose.STANDING;\n // Determining slow movement has to be done before pose is updated\n public boolean isSlowMovement = false;\n public World playerWorld;\n public boolean isInBed = false;\n public boolean lastInBed = false;\n public boolean isDead = false;\n public float depthStriderLevel;\n public float flySpeed;\n public VehicleData vehicleData = new VehicleData();\n // The client claims this\n public boolean clientClaimsLastOnGround;\n // Set from base tick\n public boolean wasTouchingWater = false;\n public boolean wasTouchingLava = false;\n // For slightly reduced vertical lava friction and jumping\n public boolean slightlyTouchingLava = false;\n // For jumping\n public boolean slightlyTouchingWater = false;\n public boolean wasEyeInWater = false;\n public FluidTag fluidOnEyes;\n public boolean horizontalCollision;\n public boolean verticalCollision;\n public boolean clientControlledHorizontalCollision;\n public boolean clientControlledVerticalCollision;\n // Okay, this is our 0.03 detection\n //\n // couldSkipTick determines if an input could have resulted in the player skipping a tick < 0.03\n //\n // skippedTickInActualMovement determines if, relative to actual movement, the player didn't move enough\n // and a 0.03 vector was \"close enough\" to be an accurate prediction\n public boolean couldSkipTick = false;\n // This determines if the\n public boolean skippedTickInActualMovement = false;\n public boolean canGroundRiptide = false;\n // You cannot initialize everything here for some reason\n public CompensatedFlying compensatedFlying;\n public CompensatedFireworks compensatedFireworks;\n public CompensatedRiptide compensatedRiptide;\n public CompensatedWorld compensatedWorld;\n public CompensatedEntities compensatedEntities;\n public CompensatedPotions compensatedPotions;\n public LatencyUtils latencyUtils = new LatencyUtils();\n public PointThreeEstimator pointThreeEstimator;\n public TrigHandler trigHandler;\n public PacketStateData packetStateData;\n // Keep track of basetick stuff\n public Vector baseTickAddition = new Vector();\n public Vector baseTickWaterPushing = new Vector();\n public AtomicInteger lastTransactionSent = new AtomicInteger(0);\n public AtomicInteger lastTransactionReceived = new AtomicInteger(0);\n // For syncing the player's full swing in 1.9+\n public int movementPackets = 0;\n public VelocityData firstBreadKB = null;\n public VelocityData likelyKB = null;\n public VelocityData firstBreadExplosion = null;\n public VelocityData likelyExplosions = null;\n public CheckManager checkManager;\n public MovementCheckRunner movementCheckRunner;\n public boolean tryingToRiptide = false;\n public int minPlayerAttackSlow = 0;\n public int maxPlayerAttackSlow = 0;\n public boolean inVehicle;\n public Integer vehicle = null;\n public PacketEntity playerVehicle;\n public PacketEntity lastVehicle;\n public GameMode gamemode;\n PacketTracker packetTracker;\n private ClientVersion clientVersion;\n private int transactionPing = 0;\n private long playerClockAtLeast = 0;\n public Vector3d bedPosition;\n\n public GrimPlayer(Player player) {\n this.bukkitPlayer = player;\n this.playerUUID = player.getUniqueId();\n this.entityID = player.getEntityId();\n this.playerWorld = player.getWorld();\n\n clientVersion = PacketEvents.get().getPlayerUtils().getClientVersion(bukkitPlayer);\n\n // We can't send transaction packets to this player, disable the anticheat for them\n if (!ViaBackwardsManager.isViaLegacyUpdated && getClientVersion().isOlderThanOrEquals(ClientVersion.v_1_16_4)) {\n LogUtil.warn(ChatColor.RED + \"Please update ViaBackwards to 4.0.2 or newer\");\n LogUtil.warn(ChatColor.RED + \"An important packet is broken for 1.16 and below clients on this ViaBackwards version\");\n LogUtil.warn(ChatColor.RED + \"Disabling all checks for 1.16 and below players as otherwise they WILL be falsely banned\");\n LogUtil.warn(ChatColor.RED + \"Supported version: \" + ChatColor.WHITE + \"https://github.com/ViaVersion/ViaBackwards/actions/runs/1039987269\");\n return;\n }\n\n // Geyser players don't have Java movement\n if (PacketEvents.get().getPlayerUtils().isGeyserPlayer(playerUUID)) return;\n\n Location loginLocation = player.getLocation();\n lastX = loginLocation.getX();\n lastY = loginLocation.getY();\n lastZ = loginLocation.getZ();\n\n isFlying = bukkitPlayer.isFlying();\n wasFlying = bukkitPlayer.isFlying();\n\n if (ViaVersionLookupUtils.isAvailable()) {\n UserConnection connection = Via.getManager().getConnectionManager().getConnectedClient(playerUUID);\n packetTracker = connection != null ? connection.getPacketTracker() : null;\n }\n\n if (XMaterial.isNewVersion()) {\n compensatedWorld = new CompensatedWorldFlat(this);\n } else {\n compensatedWorld = new CompensatedWorld(this);\n }\n\n compensatedFlying = new CompensatedFlying(this);\n compensatedFireworks = new CompensatedFireworks(this);\n compensatedRiptide = new CompensatedRiptide(this);\n compensatedEntities = new CompensatedEntities(this);\n compensatedPotions = new CompensatedPotions(this);\n trigHandler = new TrigHandler(this);\n uncertaintyHandler = new UncertaintyHandler(this);\n pointThreeEstimator = new PointThreeEstimator(this);\n\n packetStateData = new PacketStateData();\n packetStateData.lastSlotSelected = bukkitPlayer.getInventory().getHeldItemSlot();\n\n checkManager = new CheckManager(this);\n movementCheckRunner = new MovementCheckRunner(this);\n\n playerWorld = bukkitPlayer.getLocation().getWorld();\n if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17)) {\n compensatedWorld.setMinHeight(bukkitPlayer.getWorld().getMinHeight());\n compensatedWorld.setMaxWorldHeight(bukkitPlayer.getWorld().getMaxHeight());\n }\n\n x = bukkitPlayer.getLocation().getX();\n y = bukkitPlayer.getLocation().getY();\n z = bukkitPlayer.getLocation().getZ();\n xRot = bukkitPlayer.getLocation().getYaw();\n yRot = bukkitPlayer.getLocation().getPitch();\n isDead = bukkitPlayer.isDead();\n\n lastX = bukkitPlayer.getLocation().getX();\n lastY = bukkitPlayer.getLocation().getY();\n lastZ = bukkitPlayer.getLocation().getZ();\n lastXRot = bukkitPlayer.getLocation().getYaw();\n lastYRot = bukkitPlayer.getLocation().getPitch();\n\n gamemode = bukkitPlayer.getGameMode();\n\n uncertaintyHandler.pistonPushing.add(0d);\n uncertaintyHandler.collidingEntities.add(0);\n\n getSetbackTeleportUtil().setSafeSetbackLocation(playerWorld, new Vector3d(x, y, z));\n\n boundingBox = GetBoundingBox.getBoundingBoxFromPosAndSize(x, y, z, 0.6, 1.8);\n\n GrimAPI.INSTANCE.getPlayerDataManager().addPlayer(this);\n }\n\n public Set<VectorData> getPossibleVelocities() {\n Set<VectorData> set = new HashSet<>();\n\n if (firstBreadKB != null) {\n set.add(new VectorData(firstBreadKB.vector.clone(), VectorData.VectorType.Knockback));\n }\n\n if (likelyKB != null) {\n // Allow water pushing to affect knockback\n set.add(new VectorData(likelyKB.vector.clone(), VectorData.VectorType.Knockback));\n }\n\n set.addAll(getPossibleVelocitiesMinusKnockback());\n return set;\n }\n\n public Set<VectorData> getPossibleVelocitiesMinusKnockback() {\n Set<VectorData> possibleMovements = new HashSet<>();\n possibleMovements.add(new VectorData(clientVelocity, VectorData.VectorType.Normal));\n\n // A player cannot swim hop (> 0 y vel) and be on the ground\n // Fixes bug with underwater stepping movement being confused with swim hopping movement\n if (canSwimHop && !onGround) {\n possibleMovements.add(new VectorData(clientVelocity.clone().setY(0.3f), VectorData.VectorType.Swimhop));\n }\n\n // If the player has that client sided riptide thing and has colliding with an entity this tick\n if (riptideSpinAttackTicks >= 0 && uncertaintyHandler.collidingEntities.getLast() > 0) {\n possibleMovements.add(new VectorData(clientVelocity.clone().multiply(-0.2), VectorData.VectorType.Trident));\n }\n\n if (lastWasClimbing != 0) {\n possibleMovements.add(new VectorData(clientVelocity.clone().setY(lastWasClimbing + baseTickAddition.getY()), VectorData.VectorType.Climbable));\n }\n\n // Knockback takes precedence over piston pushing in my testing\n // It's very difficult to test precedence so if there's issues with this bouncy implementation let me know\n for (VectorData data : new HashSet<>(possibleMovements)) {\n for (BlockFace direction : uncertaintyHandler.slimePistonBounces) {\n if (direction.getModX() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setX(direction.getModX()), VectorData.VectorType.SlimePistonBounce));\n } else if (direction.getModY() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setY(direction.getModY()), VectorData.VectorType.SlimePistonBounce));\n } else if (direction.getModZ() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setZ(direction.getModZ()), VectorData.VectorType.SlimePistonBounce));\n }\n }\n }\n\n return possibleMovements;\n }\n\n // Players can get 0 ping by repeatedly sending invalid transaction packets, but that will only hurt them\n // The design is allowing players to miss transaction packets, which shouldn't be possible\n // But if some error made a client miss a packet, then it won't hurt them too bad.\n // Also it forces players to take knockback\n public boolean addTransactionResponse(short id) {\n // Disable ViaVersion packet limiter\n // Required as ViaVersion listens before us for converting packets between game versions\n if (packetTracker != null)\n packetTracker.setIntervalPackets(0);\n\n Pair<Short, Long> data = null;\n boolean hasID = false;\n for (Pair<Short, Long> iterator : transactionsSent) {\n if (iterator.getFirst() == id) {\n hasID = true;\n break;\n }\n }\n\n if (hasID) {\n do {\n data = transactionsSent.poll();\n if (data == null)\n break;\n\n int incrementingID = lastTransactionReceived.incrementAndGet();\n transactionPing = (int) (System.nanoTime() - data.getSecond());\n playerClockAtLeast = data.getSecond();\n\n latencyUtils.handleNettySyncTransaction(incrementingID);\n } while (data.getFirst() != id);\n }\n\n // Were we the ones who sent the packet?\n return data != null && data.getFirst() == id;\n }\n\n public void baseTickAddWaterPushing(Vector vector) {\n baseTickWaterPushing.add(vector);\n }\n\n public void baseTickAddVector(Vector vector) {\n clientVelocity.add(vector);\n baseTickAddition.add(vector);\n }\n\n public float getMaxUpStep() {\n if (playerVehicle == null) return 0.6f;\n\n if (playerVehicle.type == EntityType.BOAT) {\n return 0f;\n }\n\n // Pigs, horses, striders, and other vehicles all have 1 stepping height\n return 1.0f;\n }\n\n public void sendTransaction() {\n short transactionID = getNextTransactionID(1);\n try {\n addTransactionSend(transactionID);\n\n if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17)) {\n PacketEvents.get().getPlayerUtils().sendPacket(bukkitPlayer, new WrappedPacketOutPing(transactionID));\n } else {\n PacketEvents.get().getPlayerUtils().sendPacket(bukkitPlayer, new WrappedPacketOutTransaction(0, transactionID, false));\n }\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n\n public short getNextTransactionID(int add) {\n // Take the 15 least significant bits, multiply by 1.\n // Short range is -32768 to 32767\n // We return a range of -32767 to 0\n // Allowing a range of -32768 to 0 for velocity + explosions\n return (short) (-1 * (transactionIDCounter.getAndAdd(add) & 0x7FFF));\n }\n\n public void addTransactionSend(short id) {\n didWeSendThatTrans.add(id);\n }\n\n public boolean isEyeInFluid(FluidTag tag) {\n return this.fluidOnEyes == tag;\n }\n\n public double getEyeHeight() {\n return GetBoundingBox.getEyeHeight(isCrouching, isGliding, isSwimming, isRiptidePose, isInBed, getClientVersion());\n }\n\n public Pose getSneakingPose() {\n return getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) ? Pose.CROUCHING : Pose.NINE_CROUCHING;\n }\n\n public void pollClientVersion() {\n this.clientVersion = PacketEvents.get().getPlayerUtils().getClientVersion(bukkitPlayer);\n }\n\n public ClientVersion getClientVersion() {\n return clientVersion;\n }\n\n public void setVulnerable() {\n // Essentials gives players invulnerability after teleport, which is bad\n try {\n Plugin essentials = Bukkit.getServer().getPluginManager().getPlugin(\"Essentials\");\n if (essentials == null) return;\n\n Object user = ((Essentials) essentials).getUser(bukkitPlayer);\n if (user == null) return;\n\n // Use reflection because there isn't an API for this\n Field invulnerable = user.getClass().getDeclaredField(\"teleportInvulnerabilityTimestamp\");\n invulnerable.setAccessible(true);\n invulnerable.set(user, 0);\n } catch (Exception e) { // Might error from very outdated Essentials builds\n e.printStackTrace();\n }\n }\n\n public List<Double> getPossibleEyeHeights() { // We don't return sleeping eye height\n if (getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14)) { // Elytra, sneaking (1.14), standing\n return Arrays.asList(0.4, 1.27, 1.62);\n } else if (getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)) { // Elytra, sneaking, standing\n return Arrays.asList(0.4, 1.54, 1.62);\n } else { // Only sneaking or standing\n return Arrays.asList(1.54, 1.62);\n }\n }\n\n public int getKeepAlivePing() {\n return PacketEvents.get().getPlayerUtils().getPing(bukkitPlayer);\n }\n\n public int getTransactionPing() {\n return transactionPing;\n }\n\n public long getPlayerClockAtLeast() {\n return playerClockAtLeast;\n }\n\n public SetbackTeleportUtil getSetbackTeleportUtil() {\n return checkManager.getSetbackUtil();\n }\n\n public boolean wouldCollisionResultFlagGroundSpoof(double inputY, double collisionY) {\n boolean verticalCollision = inputY != collisionY;\n boolean calculatedOnGround = verticalCollision && inputY < 0.0D;\n\n // We don't care about ground results here\n if (exemptOnGround()) return false;\n\n // If the player is on the ground with a y velocity of 0, let the player decide (too close to call)\n if (inputY == -SimpleCollisionBox.COLLISION_EPSILON && collisionY > -SimpleCollisionBox.COLLISION_EPSILON && collisionY <= 0)\n return false;\n\n return calculatedOnGround != onGround;\n }\n\n public boolean exemptOnGround() {\n return inVehicle\n || uncertaintyHandler.pistonX != 0 || uncertaintyHandler.pistonY != 0\n || uncertaintyHandler.pistonZ != 0 || uncertaintyHandler.isSteppingOnSlime\n || isFlying || uncertaintyHandler.isStepMovement || isDead\n || isInBed || lastInBed || uncertaintyHandler.lastFlyingStatusChange > -30\n || uncertaintyHandler.lastHardCollidingLerpingEntity > -3 || uncertaintyHandler.isOrWasNearGlitchyBlock;\n }\n}" }, { "identifier": "PredictionEngineLava", "path": "src/main/java/ac/grim/grimac/predictionengine/predictions/PredictionEngineLava.java", "snippet": "public class PredictionEngineLava extends PredictionEngine {\n @Override\n public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) {\n for (VectorData vector : new HashSet<>(existingVelocities)) {\n existingVelocities.add(new VectorData(vector.vector.clone().add(new Vector(0, 0.04, 0)), vector, VectorData.VectorType.Jump));\n\n if (player.slightlyTouchingLava && player.lastOnGround && !player.onGround) {\n Vector withJump = vector.vector.clone();\n super.doJump(player, withJump);\n existingVelocities.add(new VectorData(withJump, vector, VectorData.VectorType.Jump));\n }\n }\n }\n}" }, { "identifier": "VectorData", "path": "src/main/java/ac/grim/grimac/utils/data/VectorData.java", "snippet": "public class VectorData {\n public VectorType vectorType;\n public VectorData lastVector;\n public Vector vector;\n\n @Getter\n private boolean isKnockback, isExplosion, isTrident, isZeroPointZeroThree, isSwimHop, isFlipSneaking, isFlipItem, isJump = false;\n\n // For handling replacing the type of vector it is while keeping data\n public VectorData(Vector vector, VectorData lastVector, VectorType vectorType) {\n this.vector = vector;\n this.lastVector = lastVector;\n this.vectorType = vectorType;\n\n if (lastVector != null) {\n isKnockback = lastVector.isKnockback;\n isExplosion = lastVector.isExplosion;\n isTrident = lastVector.isTrident;\n isZeroPointZeroThree = lastVector.isZeroPointZeroThree;\n isSwimHop = lastVector.isSwimHop;\n isFlipSneaking = lastVector.isFlipSneaking;\n isFlipItem = lastVector.isFlipItem;\n isJump = lastVector.isJump;\n }\n\n addVectorType(vectorType);\n }\n\n public VectorData(Vector vector, VectorType vectorType) {\n this.vector = vector;\n this.vectorType = vectorType;\n addVectorType(vectorType);\n }\n\n public VectorData returnNewModified(Vector newVec, VectorType type) {\n return new VectorData(newVec, this, type);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(vectorType, vector, isKnockback, isExplosion, isTrident, isZeroPointZeroThree, isSwimHop, isFlipSneaking, isFlipItem, isJump);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n VectorData that = (VectorData) o;\n return isKnockback == that.isKnockback && isExplosion == that.isExplosion && isTrident == that.isTrident && isZeroPointZeroThree == that.isZeroPointZeroThree && isSwimHop == that.isSwimHop && isFlipSneaking == that.isFlipSneaking && isFlipItem == that.isFlipItem && isJump == that.isJump && Objects.equal(vector, that.vector);\n }\n\n private void addVectorType(VectorType type) {\n switch (type) {\n case Knockback:\n isKnockback = true;\n break;\n case Explosion:\n isExplosion = true;\n break;\n case Trident:\n isTrident = true;\n break;\n case ZeroPointZeroThree:\n isZeroPointZeroThree = true;\n break;\n case Swimhop:\n isSwimHop = true;\n break;\n case Flip_Sneaking:\n isFlipSneaking = true;\n break;\n case Flip_Use_Item:\n isFlipItem = true;\n break;\n case Jump:\n isJump = true;\n break;\n }\n }\n\n // TODO: This is a stupid idea that slows everything down, remove it! There are easier ways to debug grim.\n // Would make false positives really easy to fix\n // But seriously, we could trace the code to find the mistake\n public enum VectorType {\n Normal,\n Swimhop,\n Climbable,\n Knockback,\n HackyClimbable,\n Teleport,\n SkippedTicks,\n Explosion,\n InputResult,\n StuckMultiplier,\n Spectator,\n Dead,\n Jump,\n SurfaceSwimming,\n SwimmingSpace,\n BestVelPicked,\n LegacySwimming,\n Elytra,\n Firework,\n Lenience,\n TridentJump,\n Trident,\n SlimePistonBounce,\n Entity_Pushing,\n ZeroPointZeroThree,\n AttackSlow,\n Flip_Sneaking,\n Flip_Use_Item\n }\n\n @Override\n public String toString() {\n return \"VectorData{\" +\n \"vectorType=\" + vectorType +\n \", vector=\" + vector +\n '}';\n }\n}" } ]
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.predictionengine.predictions.PredictionEngineLava; import ac.grim.grimac.utils.data.VectorData; import org.bukkit.util.Vector; import java.util.List; import java.util.Set;
6,071
package ac.grim.grimac.predictionengine.predictions.rideable; public class PredictionEngineRideableLava extends PredictionEngineLava { Vector movementVector; public PredictionEngineRideableLava(Vector movementVector) { this.movementVector = movementVector; } @Override
package ac.grim.grimac.predictionengine.predictions.rideable; public class PredictionEngineRideableLava extends PredictionEngineLava { Vector movementVector; public PredictionEngineRideableLava(Vector movementVector) { this.movementVector = movementVector; } @Override
public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) {
2
2023-11-11 05:14:12+00:00
8k
kawainime/IOT-Smart_Farming
IOT_Farm_V.2/src/Core/Background/boot_Up.java
[ { "identifier": "Connector", "path": "IOT_Farm_V.2/src/Core/MySql/Connector.java", "snippet": "public class Connector\n{\n public static Connection connection()\n {\n Connection conn = null;\n \n String host = Load_Settings.load_data(\"HOST\");\n \n String port = Load_Settings.load_data(\"PORT\");\n \n String user_name = Load_Settings.load_data(\"UNAME\");\n \n String password = Load_Settings.load_data(\"PASSWORD\");\n \n String db_name = Load_Settings.load_data(\"DBNAME\");\n\n String database_url = \"jdbc:mysql://\"+host+\":\"+port+\"/\"+db_name+\"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC\";\n\n try\n {\n conn = DriverManager.getConnection(database_url, user_name, password);\n \n }\n catch (Exception ERROR)\n {\n System.out.println(\"Error Message : \"+ERROR);\n }\n return conn;\n }\n \n}" }, { "identifier": "home", "path": "IOT_Farm_V.2/src/UI/home.java", "snippet": "public class home extends javax.swing.JFrame {\n\n\n public home()\n {\n initComponents();\n \n pane.removeAll();\n\n Welcome screen = new Welcome();\n\n pane.add(screen).setVisible(true);\n \n automation Automatic = new automation();\n \n Automatic.tasker();\n \n py_executer execute_python = new py_executer();\n \n execute_python.start();\n \n setIconImage(new ImageIcon(getClass().getResource(\"/img/icons/iceberg_48px.png\")).getImage());\n }\n\n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n jPanel1 = new javax.swing.JPanel();\n roundPanel2 = new com.deshan.swing.RoundPanel();\n jLabel1 = new javax.swing.JLabel();\n roundPanel4 = new com.deshan.swing.RoundPanel();\n jLabel2 = new javax.swing.JLabel();\n jLabel4 = new javax.swing.JLabel();\n jLabel5 = new javax.swing.JLabel();\n jLabel6 = new javax.swing.JLabel();\n jLabel7 = new javax.swing.JLabel();\n jLabel8 = new javax.swing.JLabel();\n jLabel9 = new javax.swing.JLabel();\n jLabel10 = new javax.swing.JLabel();\n jLabel11 = new javax.swing.JLabel();\n jLabel12 = new javax.swing.JLabel();\n roundPanel3 = new com.deshan.swing.RoundPanel();\n pane = new javax.swing.JDesktopPane();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n setTitle(\"Smart Agriculture System\");\n setResizable(false);\n getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());\n\n jPanel1.setBackground(new java.awt.Color(255, 255, 255));\n\n roundPanel2.setBackground(new java.awt.Color(242, 242, 242));\n\n jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);\n jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/iceberg_40px.png\"))); // NOI18N\n jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel1MouseClicked(evt);\n }\n });\n\n javax.swing.GroupLayout roundPanel2Layout = new javax.swing.GroupLayout(roundPanel2);\n roundPanel2.setLayout(roundPanel2Layout);\n roundPanel2Layout.setHorizontalGroup(\n roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(roundPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jLabel1)\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n roundPanel2Layout.setVerticalGroup(\n roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(roundPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n\n roundPanel4.setBackground(new java.awt.Color(242, 242, 242));\n\n jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/update_user_40px.png\"))); // NOI18N\n jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel2MouseClicked(evt);\n }\n });\n\n jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/plot_40px.png\"))); // NOI18N\n jLabel4.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel4MouseClicked(evt);\n }\n });\n\n jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/globe_earth_40px.png\"))); // NOI18N\n jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel5MouseClicked(evt);\n }\n });\n\n jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/motion_sensor_40px.png\"))); // NOI18N\n jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel6MouseClicked(evt);\n }\n });\n\n jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/leaf_40px.png\"))); // NOI18N\n jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel7MouseClicked(evt);\n }\n });\n\n jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/notification_center_40px.png\"))); // NOI18N\n jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel8MouseClicked(evt);\n }\n });\n\n jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/time_machine_40px.png\"))); // NOI18N\n jLabel9.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel9MouseClicked(evt);\n }\n });\n\n jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/graph_40px.png\"))); // NOI18N\n jLabel10.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel10MouseClicked(evt);\n }\n });\n\n jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/shutdown_40px.png\"))); // NOI18N\n jLabel11.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel11MouseClicked(evt);\n }\n });\n\n jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/img/icons/adjust_40px.png\"))); // NOI18N\n jLabel12.addMouseListener(new java.awt.event.MouseAdapter() {\n public void mouseClicked(java.awt.event.MouseEvent evt) {\n jLabel12MouseClicked(evt);\n }\n });\n\n javax.swing.GroupLayout roundPanel4Layout = new javax.swing.GroupLayout(roundPanel4);\n roundPanel4.setLayout(roundPanel4Layout);\n roundPanel4Layout.setHorizontalGroup(\n roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(roundPanel4Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jLabel2)\n .addComponent(jLabel8)\n .addComponent(jLabel5)\n .addComponent(jLabel6)\n .addComponent(jLabel4)\n .addComponent(jLabel9)\n .addComponent(jLabel7)\n .addComponent(jLabel10)\n .addComponent(jLabel11)\n .addComponent(jLabel12))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n roundPanel4Layout.setVerticalGroup(\n roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(roundPanel4Layout.createSequentialGroup()\n .addGap(26, 26, 26)\n .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(21, 21, 21)\n .addComponent(jLabel8)\n .addGap(25, 25, 25)\n .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(25, 25, 25)\n .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addContainerGap(26, Short.MAX_VALUE))\n );\n\n roundPanel3.setBackground(new java.awt.Color(242, 242, 242));\n\n javax.swing.GroupLayout paneLayout = new javax.swing.GroupLayout(pane);\n pane.setLayout(paneLayout);\n paneLayout.setHorizontalGroup(\n paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 1250, Short.MAX_VALUE)\n );\n paneLayout.setVerticalGroup(\n paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 0, Short.MAX_VALUE)\n );\n\n javax.swing.GroupLayout roundPanel3Layout = new javax.swing.GroupLayout(roundPanel3);\n roundPanel3.setLayout(roundPanel3Layout);\n roundPanel3Layout.setHorizontalGroup(\n roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel3Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(pane)\n .addContainerGap())\n );\n roundPanel3Layout.setVerticalGroup(\n roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(roundPanel3Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(pane)\n .addContainerGap())\n );\n\n javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);\n jPanel1.setLayout(jPanel1Layout);\n jPanel1Layout.setHorizontalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addGap(10, 10, 10)\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(roundPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addComponent(roundPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGap(10, 10, 10)\n .addComponent(roundPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n jPanel1Layout.setVerticalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addGap(18, 18, 18)\n .addComponent(roundPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(6, 6, 6)\n .addComponent(roundPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(11, 11, 11))\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()\n .addGap(11, 11, 11)\n .addComponent(roundPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n\n getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1360, 730));\n\n pack();\n setLocationRelativeTo(null);\n }// </editor-fold>//GEN-END:initComponents\n\n private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked\n \n pane.removeAll();\n\n Globle screen = new Globle();\n\n pane.add(screen).setVisible(true); \n }//GEN-LAST:event_jLabel5MouseClicked\n\n private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked\n \n pane.removeAll();\n\n Sensor_Box_Draw screen = new Sensor_Box_Draw();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel4MouseClicked\n\n private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked\n \n pane.removeAll();\n\n Sensor_Box screen = new Sensor_Box();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel6MouseClicked\n\n private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked\n \n pane.removeAll();\n\n task screen = new task();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel8MouseClicked\n\n private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked\n \n pane.removeAll();\n\n History screen = new History();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel2MouseClicked\n\n private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked\n \n pane.removeAll();\n\n Conditions screen = new Conditions();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel9MouseClicked\n\n private void jLabel12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel12MouseClicked\n \n pane.removeAll();\n\n Settings screen = new Settings();\n\n pane.add(screen).setVisible(true);\n\n }//GEN-LAST:event_jLabel12MouseClicked\n\n private void jLabel11MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel11MouseClicked\n \n pane.removeAll();\n\n Cyber_Switch screen = new Cyber_Switch();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel11MouseClicked\n\n private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked\n \n pane.removeAll();\n\n Crop screen = new Crop();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel7MouseClicked\n\n private void jLabel10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel10MouseClicked\n \n pane.removeAll();\n\n Suggetions screen = new Suggetions();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel10MouseClicked\n \n private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked\n \n pane.removeAll();\n\n devices screen = new devices();\n\n pane.add(screen).setVisible(true);\n }//GEN-LAST:event_jLabel1MouseClicked\n\n public void notifications(String message, int option)\n {\n if(option == 1)\n {\n Notification panel = new Notification(this, Notification.Type.SUCCESS, Notification.Location.TOP_CENTER, message);\n \n panel.showNotification();\n }\n else if(option == 2)\n {\n Notification panel = new Notification(this, Notification.Type.WARNING, Notification.Location.TOP_CENTER, message);\n \n panel.showNotification();\n }\n else if(option == 3)\n {\n Notification panel = new Notification(this, Notification.Type.INFO, Notification.Location.TOP_CENTER, message);\n \n panel.showNotification();\n }\n else if(option == 4)\n {\n Notification panel = new Notification(this, Notification.Type.SUCCESS, Notification.Location.TOP_RIGHT, message);\n \n panel.showNotification();\n }\n else if(option == 5)\n {\n Notification panel = new Notification(this, Notification.Type.WARNING, Notification.Location.TOP_RIGHT, message);\n \n panel.showNotification();\n }\n else if(option == 6)\n {\n Notification panel = new Notification(this, Notification.Type.INFO, Notification.Location.TOP_RIGHT, message);\n \n panel.showNotification();\n } \n }\n /**\n * @param args the command line arguments\n */\n public static void main(String args[]) {\n /* Set the Nimbus look and feel */\n //<editor-fold defaultstate=\"collapsed\" desc=\" Look and feel setting code (optional) \">\n /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.\n * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html \n */\n try {\n for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {\n if (\"Windows\".equals(info.getName())) {\n javax.swing.UIManager.setLookAndFeel(info.getClassName());\n break;\n }\n }\n } catch (ClassNotFoundException ex) {\n java.util.logging.Logger.getLogger(home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (InstantiationException ex) {\n java.util.logging.Logger.getLogger(home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n java.util.logging.Logger.getLogger(home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (javax.swing.UnsupportedLookAndFeelException ex) {\n java.util.logging.Logger.getLogger(home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n }\n //</editor-fold>\n\n /* Create and display the form */\n java.awt.EventQueue.invokeLater(new Runnable() {\n public void run() {\n new home().setVisible(true);\n }\n });\n }\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel jLabel1;\n private javax.swing.JLabel jLabel10;\n private javax.swing.JLabel jLabel11;\n private javax.swing.JLabel jLabel12;\n private javax.swing.JLabel jLabel2;\n private javax.swing.JLabel jLabel4;\n private javax.swing.JLabel jLabel5;\n private javax.swing.JLabel jLabel6;\n private javax.swing.JLabel jLabel7;\n private javax.swing.JLabel jLabel8;\n private javax.swing.JLabel jLabel9;\n private javax.swing.JPanel jPanel1;\n private javax.swing.JDesktopPane pane;\n private com.deshan.swing.RoundPanel roundPanel2;\n private com.deshan.swing.RoundPanel roundPanel3;\n private com.deshan.swing.RoundPanel roundPanel4;\n // End of variables declaration//GEN-END:variables\n}" } ]
import Core.MySql.Connector; import UI.home; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
4,515
/* * 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 Core.Background; /** * * @author Jayashanka Deshan */ public class boot_Up implements Runnable { private final Thread thread; public boot_Up() { thread = new Thread(this); } @Override public void run() {
/* * 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 Core.Background; /** * * @author Jayashanka Deshan */ public class boot_Up implements Runnable { private final Thread thread; public boot_Up() { thread = new Thread(this); } @Override public void run() {
Connection connection = Connector.connection();
0
2023-11-11 08:23:10+00:00
8k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/configuration/ServiceConfig.java
[ { "identifier": "PackType", "path": "src/main/java/io/mindspice/itemserver/schema/PackType.java", "snippet": "public enum PackType {\n BOOSTER(12),\n STARTER(39);\n\n public int cardAmount;\n\n PackType(int cardAmount) {\n this.cardAmount = cardAmount;\n }\n\n}" }, { "identifier": "Settings", "path": "src/main/java/io/mindspice/itemserver/Settings.java", "snippet": "public class Settings {\n static Settings INSTANCE;\n\n /* Monitor */\n public volatile int startHeight;\n public volatile int chainScanInterval;\n public volatile int heightBuffer;\n public volatile boolean isPaused;\n\n /* Database Config */\n public String okraDBUri;\n public String okraDBUser;\n public String okraDBPass;\n public String chiaDBUri;\n public String chiaDBUser;\n public String chiaDBPass;\n\n /* Internal Services */\n public String authServiceUri;\n public int authServicePort;\n public String authServiceUser;\n public String authServicePass;\n\n /* Card Rarity */\n public int holoPct = 3;\n public int goldPct = 20;\n public int highLvl = 40;\n public String currCollection;\n\n /* Config Paths */\n public String mainNodeConfig;\n public String mintWalletConfig;\n public String transactionWalletConfig;\n public String mintJobConfig;\n public String okraJobConfig;\n public String outrJobConfig;\n\n /* S3 */\n public String s3AccessKey;\n public String s3SecretKey;\n\n\n /* Assets */\n public String boosterAddress;\n public String boosterTail;\n public String starterAddress;\n public String starterTail;\n\n\n /* DID Mint */\n public String didMintToAddr;\n public List<String> didUris;\n public List<String> didMetaUris;\n public List<String> didLicenseUris;\n public String didHash;\n public String didMetaHash;\n public String didLicenseHash;\n\n /* Dispersal Limits */\n public int nftFlagAmount;\n public int okraFlagAmount;\n public int outrFlagAmount;\n\n\n\n static {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n\n File file = new File(\"config.yaml\");\n\n try {\n INSTANCE = mapper.readValue(file, Settings.class);\n } catch (IOException e) {\n try {\n writeBlank();\n } catch (IOException ex) { throw new RuntimeException(ex); }\n throw new RuntimeException(\"Failed to read config file.\", e);\n }\n }\n\n public static Settings get() {\n return INSTANCE;\n }\n\n public static MetaData getAccountMintMetaData() {\n return null;\n }\n\n public static void writeBlank() throws IOException {\n var mapper = new ObjectMapper(new YAMLFactory());\n mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);\n File yamlFile = new File(\"defaults.yaml\");\n mapper.writeValue(yamlFile, new Settings());\n }\n\n\n}" }, { "identifier": "BlockchainMonitor", "path": "src/main/java/io/mindspice/itemserver/monitor/BlockchainMonitor.java", "snippet": "public class BlockchainMonitor implements Runnable {\n private volatile int nextHeight;\n private final FullNodeAPI nodeAPI;\n private final WalletAPI walletAPI;\n private final OkraChiaAPI chiaAPI;\n private final OkraNFTAPI nftAPI;\n private final MintService mintService;\n private final Map<String, Pair<String, PackType>> assetMap;\n private final List<Card> cardList;\n private final CustomLogger logger;\n private final Semaphore semaphore = new Semaphore(1);\n\n protected final Supplier<RPCException> chiaExcept =\n () -> new RPCException(\"Required Chia RPC call returned Optional.empty\");\n\n private final ExecutorService virtualExec = Executors.newVirtualThreadPerTaskExecutor();\n\n public BlockchainMonitor(\n FullNodeAPI nodeAPI, WalletAPI walletAPI,\n OkraChiaAPI chiaAPI, OkraNFTAPI nftAPI,\n MintService mintService, Map<String,\n Pair<String, PackType>> assetMap,\n List<Card> cardList, int startHeight,\n CustomLogger logger) {\n\n nextHeight = startHeight;\n this.nodeAPI = nodeAPI;\n this.walletAPI = walletAPI;\n this.chiaAPI = chiaAPI;\n this.nftAPI = nftAPI;\n this.mintService = mintService;\n this.assetMap = assetMap;\n this.cardList = cardList;\n this.logger = logger;\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Started Blockchain Monitor\");\n }\n\n public int getNextHeight() {\n return nextHeight;\n }\n\n @Override\n public void run() {\n if (Settings.get().isPaused) { return; }\n if (semaphore.availablePermits() == 0) { return; }\n try {\n semaphore.acquire();\n if (!((nodeAPI.getHeight().data().orElseThrow() - Settings.get().heightBuffer) >= nextHeight)) {\n return;\n }\n long start = System.currentTimeMillis();\n\n AdditionsAndRemovals coinRecords = chiaAPI.getCoinRecordsByHeight(nextHeight)\n .data().orElseThrow(chiaExcept);\n\n List<CoinRecord> additions = coinRecords.additions().stream().filter(a -> !a.coinbase()).toList();\n List<CoinRecord> removals = coinRecords.removals().stream().filter(a -> !a.coinbase()).toList();\n\n if (additions.isEmpty()) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Finished scan of block height: \" + nextHeight +\n \" | Additions: 0\" +\n \" | Block scan took: \" + (System.currentTimeMillis() - start) + \" ms\");\n nextHeight++; // Non-atomic inc doesn't matter, non-critical, is volatile to observe when monitoring\n return;\n }\n\n // NOTE offer transactions need to be discovered via finding the parent in the removals\n // since they do some intermediate operations\n CompletableFuture<CardAndAccountCheck> cardAndAccountCheck = CompletableFuture.supplyAsync(() -> {\n var cardOrAccountUpdates = nftAPI.checkIfCardOrAccountExists(\n Stream.concat(additions.stream(), removals.stream())\n .map(a -> a.coin().parentCoinInfo())\n .distinct().toList()\n );\n\n if (cardOrAccountUpdates.data().isPresent()) {\n return cardOrAccountUpdates.data().get();\n }\n return null;\n }, virtualExec);\n\n CompletableFuture<List<PackPurchase>> packCheck = CompletableFuture.supplyAsync(() -> {\n List<PackPurchase> packPurchases = null;\n var packRecords = additions.stream().filter(a -> assetMap.containsKey(a.coin().puzzleHash())).toList();\n\n if (!packRecords.isEmpty()) {\n packPurchases = new ArrayList<>(packRecords.size());\n for (var record : packRecords) {\n int amount = (int) (record.coin().amount() / 1000);\n try {\n ApiResponse<CatSenderInfo> catInfoResp = nodeAPI.getCatSenderInfo(record);\n if (!catInfoResp.success()) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \" Failed asset lookup, wrong asset?\" +\n \" | Coin: \" + ChiaUtils.getCoinId(record.coin()) +\n \" | Amount(mojos / 1000): \" + amount +\n \" | Error: \" + catInfoResp.error());\n continue;\n }\n\n CatSenderInfo catInfo = catInfoResp.data().orElseThrow(chiaExcept);\n if (!catInfo.assetId().equals(assetMap.get(record.coin().puzzleHash()).first())) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Wrong Asset Received: \" + catInfo.assetId()\n + \" | Coin: \" + ChiaUtils.getCoinId(record.coin())\n + \" | Expected: \" + assetMap.get(record.coin().puzzleHash()).first()\n + \" | Amount: \" + record.coin().amount());\n continue;\n }\n\n PackType packType = assetMap.get(record.coin().puzzleHash()).second();\n for (int i = 0; i < amount; ++i) {\n String uuid = UUID.randomUUID().toString();\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Submitted pack purchase \" +\n \" | UUID: \" + uuid +\n \" | Coin: \" + ChiaUtils.getCoinId(record.coin()) +\n \" | Amount(mojos / 1000): \" + amount +\n \" | Asset: \" + catInfo.assetId() +\n \" | Sender Address\" + catInfo.senderPuzzleHash()\n );\n packPurchases.add(new PackPurchase(\n catInfo.senderPuzzleHash(),\n packType, uuid,\n nextHeight,\n ChiaUtils.getCoinId(record.coin()))\n );\n }\n } catch (RPCException e) {\n logger.logApp(this.getClass(), TLogLevel.FAILED, \"Failed asset lookups at height: \" + nextHeight +\n \" | Reason: \" + e.getMessage() +\n \" | Coin: \" + ChiaUtils.getCoinId(record.coin()) +\n \" | Amount(mojos / 1000): \" + amount);\n }\n }\n return packPurchases;\n }\n return null;\n }, virtualExec);\n\n CardAndAccountCheck cardAndAccountResults = cardAndAccountCheck.get();\n List<PackPurchase> packPurchasesResults = packCheck.get();\n\n boolean foundChange = false;\n if (cardAndAccountResults != null) {\n if (!cardAndAccountResults.existingCards().isEmpty() || !cardAndAccountResults.existingAccounts().isEmpty()) {\n virtualExec.submit(new UpdateDbInfo(\n cardAndAccountResults.existingCards(),\n cardAndAccountResults.existingAccounts())\n );\n foundChange = true;\n }\n }\n\n if (packPurchasesResults != null && !packPurchasesResults.isEmpty()) {\n packPurchasesResults.forEach(\n p -> virtualExec.submit(() -> nftAPI.addPackPurchases(\n p.uuid(),\n p.address(),\n p.packType().name(),\n p.height(),\n p.coinId())\n )\n );\n logger.logApp(this.getClass(), TLogLevel.DEBUG, \"Submitting purchases\");\n virtualExec.submit(new PackMint(cardList, packPurchasesResults, mintService, nftAPI, logger, virtualExec));\n foundChange = true;\n }\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Finished scan of block height: \" + nextHeight +\n \" | Additions: \" + additions.size() +\n \" | Block scan took: \" + (System.currentTimeMillis() - start) + \" ms\");\n\n if (foundChange) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Changes detected\" +\n \" | Height: \" + nextHeight +\n \" | Card NFTs: \" + (cardAndAccountResults != null ? cardAndAccountResults.existingCards().toString() : \"[]\") +\n \" | Account NFTs: \" + (cardAndAccountResults != null ? cardAndAccountResults.existingAccounts().toString() : \"[]\") +\n \" | Pack Purchases \" + (packPurchasesResults != null ? packPurchasesResults : \"[]\"));\n }\n\n nextHeight++;\n\n } catch (\n Exception e) {\n logger.logApp(this.getClass(), TLogLevel.FAILED, \"Failed to scan height: \" + nextHeight +\n \" | Reason: \" + e.getMessage(), e);\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Failed to scan height: \" + nextHeight +\n \" | Reason: \" + e.getMessage(), e);\n } finally {\n semaphore.release();\n }\n }\n\n public int getHeight() {\n return nextHeight;\n }\n\n private class UpdateDbInfo implements Runnable {\n private final List<String> cardUpdates;\n private final List<AccountDid> accountUpdates;\n\n public UpdateDbInfo(List<String> cardUpdates, List<AccountDid> accountUpdates) {\n this.cardUpdates = cardUpdates;\n this.accountUpdates = accountUpdates;\n }\n\n @Override\n public void run() {\n long startTime = System.currentTimeMillis();\n for (var launcherId : cardUpdates) {\n try {\n NftInfo newInfo = Utils.nftGetInfoWrapper(walletAPI, launcherId);\n NftUpdate updatedInfo = new NftUpdate(\n newInfo.nftCoinId(),\n launcherId,\n newInfo.ownerDid(),\n nextHeight\n );\n var updateRtn = nftAPI.updateCardDid(updatedInfo);\n if (!updateRtn.success()) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Failed Updating card launcher: \"\n + launcherId + \" | Height : \" + (nextHeight - 1) + \" | Reason: \" + updateRtn.error_msg());\n virtualExec.submit(() -> nftAPI.addFailedUpdate(launcherId,\n nextHeight - 1, false, updateRtn.error_msg())\n );\n }\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Failed Updating card launcher: \"\n + launcherId + \" | Height : \" + (nextHeight - 1) + \" | Reason: \" + e.getMessage());\n virtualExec.submit(() -> nftAPI.addFailedUpdate(launcherId,\n nextHeight - 1, false, e.getMessage())\n );\n }\n }\n\n for (var didInfo : accountUpdates) {\n try {\n NftInfo newInfo = Utils.nftGetInfoWrapper(walletAPI, didInfo.launcherId());\n NftUpdate updatedInfo = new NftUpdate(\n newInfo.nftCoinId(),\n didInfo.launcherId(),\n newInfo.ownerDid(),\n nextHeight,\n newInfo.ownerDid() != null && newInfo.ownerDid().equals(didInfo.did())\n );\n var updateRtn = nftAPI.updateAccountDid(updatedInfo);\n if (!updateRtn.success()) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Failed account launcher: \"\n + didInfo.launcherId() + \" | Height : \" + (nextHeight - 1) + \" | Reason: \" + updateRtn.error_msg());\n virtualExec.submit(() -> nftAPI.addFailedUpdate(didInfo.launcherId(),\n nextHeight - 1, false, updateRtn.error_msg())\n );\n }\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Failed account launcher: \"\n + didInfo.launcherId() + \" | Height : \" + (nextHeight - 1) + \" | Reason: \" + e.getMessage());\n virtualExec.submit(() -> nftAPI.addFailedUpdate(didInfo.launcherId(),\n nextHeight - 1, false, e.getMessage())\n );\n }\n }\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Successfully updated NFTs: \"\n + \"Cards:\" + cardUpdates + \" | accounts: \" + accountUpdates\n + \" | Update took: \" + (System.currentTimeMillis() - startTime));\n\n }\n }\n}" }, { "identifier": "CustomLogger", "path": "src/main/java/io/mindspice/itemserver/util/CustomLogger.java", "snippet": "public class CustomLogger implements TLogger {\n private static final Logger MINT_LOG = LoggerFactory.getLogger(\"MINT\");\n private static final Logger FAILED_LOG = LoggerFactory.getLogger(\"FAILED\");\n private static final Logger APP_LOG = LoggerFactory.getLogger(\"APP\");\n\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg);\n case INFO -> APP_LOG.info(msg);\n case WARNING -> APP_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> APP_LOG.debug(msg);\n }\n }\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg, e);\n case INFO -> APP_LOG.info(msg, e);\n case WARNING -> APP_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> APP_LOG.debug(msg, e);\n }\n }\n\n\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg);\n case INFO -> MINT_LOG.info(msg);\n case WARNING -> MINT_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> MINT_LOG.debug(msg);\n }\n }\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg, e);\n case INFO -> MINT_LOG.info(msg, e);\n case WARNING -> MINT_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> MINT_LOG.debug(msg, e);\n }\n }\n}" }, { "identifier": "TransactLogger", "path": "src/main/java/io/mindspice/itemserver/util/TransactLogger.java", "snippet": "public class TransactLogger implements TLogger {\n private static final Logger MINT_LOG = LoggerFactory.getLogger(\"TRANSACT\");\n private static final Logger FAILED_LOG = LoggerFactory.getLogger(\"FAILED\");\n private static final Logger APP_LOG = LoggerFactory.getLogger(\"APP\");\n\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg);\n case INFO -> APP_LOG.info(msg);\n case WARNING -> APP_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> APP_LOG.debug(msg);\n }\n }\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg, e);\n case INFO -> APP_LOG.info(msg, e);\n case WARNING -> APP_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> APP_LOG.debug(msg, e);\n }\n }\n\n\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg);\n case INFO -> MINT_LOG.info(msg);\n case WARNING -> MINT_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> MINT_LOG.debug(msg);\n }\n }\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg, e);\n case INFO -> MINT_LOG.info(msg, e);\n case WARNING -> MINT_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> MINT_LOG.debug(msg, e);\n }\n }\n}" } ]
import io.mindspice.databaseservice.client.api.OkraChiaAPI; import io.mindspice.databaseservice.client.api.OkraGameAPI; import io.mindspice.databaseservice.client.api.OkraNFTAPI; import io.mindspice.databaseservice.client.schema.Card; import io.mindspice.itemserver.schema.PackType; import io.mindspice.itemserver.Settings; import io.mindspice.itemserver.monitor.BlockchainMonitor; import io.mindspice.itemserver.services.*; import io.mindspice.itemserver.util.CustomLogger; import io.mindspice.itemserver.util.TransactLogger; import io.mindspice.jxch.rpc.http.FullNodeAPI; import io.mindspice.jxch.rpc.http.WalletAPI; import io.mindspice.jxch.rpc.schemas.wallet.nft.MetaData; import io.mindspice.jxch.transact.settings.JobConfig; import io.mindspice.mindlib.data.tuples.Pair; import io.mindspice.mindlib.http.UnsafeHttpJsonClient; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
5,194
package io.mindspice.itemserver.configuration; @Configuration public class ServiceConfig { @Bean(destroyMethod = "shutdown") public ScheduledExecutorService executor() { return Executors.newScheduledThreadPool(6); } @Bean public UnsafeHttpJsonClient authResponseClient() { return new UnsafeHttpJsonClient(); } @Bean public BlockchainMonitor blockchainMonitor( @Qualifier("mainNodeAPI") FullNodeAPI monNodeApi, @Qualifier("monWalletAPI") WalletAPI monWalletApi, @Qualifier("okraChiaAPI") OkraChiaAPI okraChiaAPI, @Qualifier("okraNFTAPI") OkraNFTAPI okraNFTAPI, @Qualifier("mintService") CardMintService mintService, @Qualifier("cardList") List<Card> cardList,
package io.mindspice.itemserver.configuration; @Configuration public class ServiceConfig { @Bean(destroyMethod = "shutdown") public ScheduledExecutorService executor() { return Executors.newScheduledThreadPool(6); } @Bean public UnsafeHttpJsonClient authResponseClient() { return new UnsafeHttpJsonClient(); } @Bean public BlockchainMonitor blockchainMonitor( @Qualifier("mainNodeAPI") FullNodeAPI monNodeApi, @Qualifier("monWalletAPI") WalletAPI monWalletApi, @Qualifier("okraChiaAPI") OkraChiaAPI okraChiaAPI, @Qualifier("okraNFTAPI") OkraNFTAPI okraNFTAPI, @Qualifier("mintService") CardMintService mintService, @Qualifier("cardList") List<Card> cardList,
@Qualifier("assetTable") Map<String, Pair<String, PackType>> assetTable,
0
2023-11-14 14:56:37+00:00
8k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java
[ { "identifier": "Client", "path": "src/main/java/com/github/codecnomad/codecclient/Client.java", "snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft();\n public static Rotation rotation = new Rotation();\n public static Config guiConfig;\n\n static {\n modules.put(\"FishingMacro\", new FishingMacro());\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n guiConfig = new Config();\n\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(rotation);\n\n MinecraftForge.EVENT_BUS.register(MainCommand.pathfinding);\n\n CommandManager.register(new MainCommand());\n }\n\n @SubscribeEvent\n public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {\n for (Map.Entry<String, Module> moduleMap : modules.entrySet()) {\n moduleMap.getValue().unregister();\n }\n }\n}" }, { "identifier": "PacketEvent", "path": "src/main/java/com/github/codecnomad/codecclient/events/PacketEvent.java", "snippet": "public class PacketEvent extends Event {\n public enum Phase {\n pre,\n post\n }\n\n public final Packet<?> packet;\n public final Phase phase;\n\n\n public PacketEvent(final Packet<?> packet, Phase phase) {\n this.packet = packet;\n this.phase = phase;\n }\n\n public static class ReceiveEvent extends PacketEvent {\n public ReceiveEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n\n public static class SendEvent extends PacketEvent {\n public SendEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n}" }, { "identifier": "S19PacketAccessor", "path": "src/main/java/com/github/codecnomad/codecclient/mixins/S19PacketAccessor.java", "snippet": "@Mixin(S19PacketEntityHeadLook.class)\npublic interface S19PacketAccessor {\n @Accessor(\"entityId\")\n int getEntityId();\n}" }, { "identifier": "Config", "path": "src/main/java/com/github/codecnomad/codecclient/ui/Config.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Config extends cc.polyfrost.oneconfig.config.Config {\n @Color(\n name = \"Color\",\n category = \"Visuals\"\n )\n public static OneColor VisualColor = new OneColor(100, 60, 160, 200);\n @KeyBind(\n name = \"Fishing key-bind\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);\n @Number(\n name = \"Catch delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 20\n )\n public static int FishingDelay = 10;\n @Number(\n name = \"Kill delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 40\n )\n public static int KillDelay = 20;\n @Number(\n name = \"Attack c/s\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 20\n )\n public static int AttackCps = 10;\n\n @Number(\n name = \"Smoothing\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 2,\n max = 10\n )\n public static int RotationSmoothing = 4;\n\n @Number(\n name = \"Random movement frequency\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 50\n )\n public static int MovementFrequency = 15;\n\n @Switch(\n name = \"Auto kill\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean AutoKill = true;\n\n @Switch(\n name = \"Only sound failsafe\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean OnlySound = false;\n\n @Number(\n name = \"Weapon slot\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 9\n )\n public static int WeaponSlot = 9;\n\n @Switch(\n name = \"Right click attack\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean RightClick = false;\n\n @HUD(\n name = \"Fishing HUD\",\n category = \"Visuals\"\n )\n public FishingHud hudFishing = new FishingHud();\n\n public Config() {\n super(new Mod(\"CodecClient\", ModType.UTIL_QOL), \"config.json\");\n initialize();\n\n registerKeyBind(FishingKeybinding, () -> toggle(\"FishingMacro\"));\n save();\n }\n\n private static void toggle(String name) {\n Module helperClassModule = Client.modules.get(name);\n if (helperClassModule.state) {\n helperClassModule.unregister();\n } else {\n helperClassModule.register();\n }\n }\n}" }, { "identifier": "Math", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Math.java", "snippet": "public class Math {\n\n public static float easeInOut(float t) {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n }\n\n public static float interpolate(float goal, float current, float time) {\n while (goal - current > 180) {\n current += 360;\n }\n while (goal - current < -180) {\n current -= 360;\n }\n\n float t = easeInOut(time);\n return current + (goal - current) * t;\n }\n\n public static String toClock(int seconds) {\n int hours = seconds / 3600;\n int minutes = (seconds % 3600) / 60;\n int remainingSeconds = seconds % 60;\n\n return String.format(\"%dh, %dm, %ds\", hours, minutes, remainingSeconds);\n }\n\n public static String toFancyNumber(int number) {\n int k = number / 1000;\n int m = number / 1000000;\n int remaining = number % 1000000;\n\n if (m > 0) {\n return String.format(\"%dM\", m);\n } else if (k > 0) {\n return String.format(\"%dk\", k);\n } else {\n return String.format(\"%d\", remaining);\n }\n }\n\n public static float getYaw(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double yawToBlock = java.lang.Math.atan2(-deltaX, deltaZ);\n double yaw = java.lang.Math.toDegrees(yawToBlock);\n\n yaw = (yaw + 360) % 360;\n if (yaw > 180) {\n yaw -= 360;\n }\n\n return (float) yaw;\n }\n\n public static Vec3 fromBlockPos(BlockPos pos) {\n return new Vec3(pos.getX(), pos.getY(), pos.getZ());\n }\n\n public static float getPitch(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaY = blockPos.getY() + 0.5 - Client.mc.thePlayer.posY - Client.mc.thePlayer.getEyeHeight();\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double distanceXZ = java.lang.Math.sqrt(deltaX * deltaX + deltaZ * deltaZ);\n double pitchToBlock = -java.lang.Math.atan2(deltaY, distanceXZ);\n double pitch = java.lang.Math.toDegrees(pitchToBlock);\n pitch = java.lang.Math.max(-90, java.lang.Math.min(90, pitch));\n return (float) pitch;\n }\n\n public static double getXZDistance(BlockPos pos1, BlockPos pos2) {\n double xDiff = pos1.getX() - pos2.getX();\n double zDiff = pos1.getZ() - pos2.getZ();\n return java.lang.Math.sqrt(xDiff * xDiff + zDiff * zDiff);\n }\n\n}" } ]
import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.events.PacketEvent; import com.github.codecnomad.codecclient.mixins.S19PacketAccessor; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Math; import com.github.codecnomad.codecclient.utils.*; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.item.*; import net.minecraft.network.play.server.*; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.List; import java.util.regex.Matcher;
4,215
double expandedMaxY = aabb.maxY + 1; double expandedMaxZ = aabb.maxZ + 1; lastAABB = new AxisAlignedBB(expandedMinX, expandedMinY, expandedMinZ, expandedMaxX, expandedMaxY, expandedMaxZ); double randomX = expandedMinX + java.lang.Math.random() * (expandedMaxX - expandedMinX); double randomY = expandedMinY + java.lang.Math.random() * (expandedMaxY - expandedMinY); double randomZ = expandedMinZ + java.lang.Math.random() * (expandedMaxZ - expandedMinZ); Client.rotation.setYaw(Math.getYaw(new BlockPos(randomX, randomY, randomZ)), 5); Client.rotation.setPitch(Math.getPitch(new BlockPos(randomX, randomY, randomZ)), 5); } for (Entity entity : Client.mc.theWorld.loadedEntityList) { if (entity instanceof EntityFishHook && ((EntityFishHook) entity).angler == Client.mc.thePlayer) { fishingHook = entity; } } if (fishingHook == null) { currentStep = FishingSteps.FIND_ROD; return; } if (fishingMarker != null && fishingMarker.isEntityAlive() && fishingMarker.getName().contains("!!!")) { currentStep = FishingSteps.CATCH; fishingMarker = null; return; } return; } case CATCH: { KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode()); if (Config.AutoKill) { currentStep = FishingSteps.KILL_DELAY; } else { currentStep = FishingSteps.FIND_ROD; } catches++; } case KILL_DELAY: { if (MainCounter.countUntil(Config.KillDelay)) { return; } currentStep = FishingSteps.KILL_MONSTER; } case KILL_MONSTER: { if (fishingMonster == null || !fishingMonster.isEntityAlive() || !Client.mc.thePlayer.canEntityBeSeen(fishingMonster)) { currentStep = FishingSteps.FIND_ROD; fishingMonster = null; return; } Client.mc.thePlayer.inventory.currentItem = Config.WeaponSlot - 1; AxisAlignedBB boundingBox = fishingMonster.getEntityBoundingBox(); double deltaX = boundingBox.maxX - boundingBox.minX; double deltaY = boundingBox.maxY - boundingBox.minY; double deltaZ = boundingBox.maxZ - boundingBox.minZ; BlockPos randomPositionOnBoundingBox = new BlockPos(boundingBox.minX + deltaX, boundingBox.minY + deltaY, boundingBox.minZ + deltaZ); Client.rotation.setYaw(Math.getYaw(randomPositionOnBoundingBox), Config.RotationSmoothing); Client.rotation.setPitch(Math.getPitch(randomPositionOnBoundingBox), Config.RotationSmoothing); if (!MainCounter.countUntil(20 / Config.AttackCps)) { MainCounter.add(java.lang.Math.random() * 100 > 70 ? 1 : 0); if (Config.RightClick) { KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode()); return; } KeyBinding.onTick(Client.mc.gameSettings.keyBindAttack.getKeyCode()); } } } } @SubscribeEvent public void renderWorld(RenderWorldLastEvent event) { if (lastAABB != null) { Render.drawOutlinedFilledBoundingBox(lastAABB, Config.VisualColor.toJavaColor(), event.partialTicks); } } @SubscribeEvent public void entitySpawn(EntityJoinWorldEvent event) { if (fishingHook == null || event.entity instanceof EntitySquid || event.entity.getName().equals("item.tile.stone.stone")) { return; } if (event.entity instanceof EntityArmorStand && event.entity.getDistanceToEntity(fishingHook) <= 0.1) { fishingMarker = event.entity; return; } if (fishingMonster == null && event.entity.getDistanceToEntity(fishingHook) <= 1.5 ) { fishingMonster = event.entity; } } @SubscribeEvent public void chatReceive(ClientChatReceivedEvent event) { if (event.type != 2) { return; } Matcher matcher = Regex.FishingSkillPattern.matcher(event.message.getFormattedText()); if (matcher.find()) { xpGain += Float.parseFloat(matcher.group(1)); } } @SubscribeEvent
package com.github.codecnomad.codecclient.modules; @SuppressWarnings("DuplicatedCode") public class FishingMacro extends Module { public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",}; public static int startTime = 0; public static int catches = 0; public static float xpGain = 0; public static FishingSteps currentStep = FishingSteps.FIND_ROD; public static Counter MainCounter = new Counter(); public static Counter AlternativeCounter = new Counter(); public static Counter FailsafeCounter = new Counter(); public static boolean failSafe = false; Entity fishingHook = null; Entity fishingMarker = null; Entity fishingMonster = null; public static float lastYaw = 0; public static float lastPitch = 0; public static AxisAlignedBB lastAABB = null; public BlockPos startPos = null; public static Pathfinding pathfinding = new Pathfinding(); @Override public void register() { MinecraftForge.EVENT_BUS.register(this); this.state = true; lastYaw = Client.mc.thePlayer.rotationYaw; lastPitch = Client.mc.thePlayer.rotationPitch; Sound.disableSounds(); startTime = (int) java.lang.Math.floor((double) System.currentTimeMillis() / 1000); startPos = Client.mc.thePlayer.getPosition(); } @Override public void unregister() { MinecraftForge.EVENT_BUS.unregister(this); this.state = false; Client.rotation.updatePitch = false; Client.rotation.updateYaw = false; lastPitch = 0; lastYaw = 0; Sound.enableSounds(); startTime = 0; catches = 0; xpGain = 0; currentStep = FishingSteps.FIND_ROD; MainCounter.reset(); FailsafeCounter.reset(); failSafe = false; fishingHook = null; fishingMarker = null; fishingMonster = null; lastAABB = null; startPos = null; } @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (failSafe) { return; } switch (currentStep) { case GO_BACK_TO_ORIGINAL: { currentStep = FishingSteps.EMPTY; List<BlockPos> path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1 , 0), startPos.add(0, -1, 0)); new Walker(path, () -> { currentStep = FishingSteps.FIND_ROD; }).start(); return; } case FIND_ROD: { if (startPos != null && Client.mc.thePlayer.getPosition().distanceSq(startPos) > 1.5) { currentStep = FishingSteps.GO_BACK_TO_ORIGINAL; return; } for (int slotIndex = 0; slotIndex < 9; slotIndex++) { ItemStack stack = Client.mc.thePlayer.inventory.getStackInSlot(slotIndex); if (stack != null && stack.getItem() instanceof ItemFishingRod) { Client.rotation.setYaw(lastYaw, Config.RotationSmoothing); Client.rotation.setPitch(lastPitch, Config.RotationSmoothing); Client.mc.thePlayer.inventory.currentItem = slotIndex; currentStep = FishingSteps.CAST_HOOK; return; } } Chat.sendMessage("Disabled macro -> couldn't find rod."); this.unregister(); return; } case CAST_HOOK: { if (Client.rotation.updateYaw || Client.rotation.updatePitch) { return; } KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode()); currentStep = FishingSteps.WAIT_FOR_CATCH; return; } case WAIT_FOR_CATCH: { if (MainCounter.countUntil(Config.FishingDelay)) { return; } if (!AlternativeCounter.countUntil(Config.MovementFrequency)) { if (fishingHook == null) { currentStep = FishingSteps.FIND_ROD; return; } AxisAlignedBB aabb = fishingHook.getEntityBoundingBox(); double expandedMinX = aabb.minX - 1; double expandedMinY = aabb.minY - 1; double expandedMinZ = aabb.minZ - 1; double expandedMaxX = aabb.maxX + 1; double expandedMaxY = aabb.maxY + 1; double expandedMaxZ = aabb.maxZ + 1; lastAABB = new AxisAlignedBB(expandedMinX, expandedMinY, expandedMinZ, expandedMaxX, expandedMaxY, expandedMaxZ); double randomX = expandedMinX + java.lang.Math.random() * (expandedMaxX - expandedMinX); double randomY = expandedMinY + java.lang.Math.random() * (expandedMaxY - expandedMinY); double randomZ = expandedMinZ + java.lang.Math.random() * (expandedMaxZ - expandedMinZ); Client.rotation.setYaw(Math.getYaw(new BlockPos(randomX, randomY, randomZ)), 5); Client.rotation.setPitch(Math.getPitch(new BlockPos(randomX, randomY, randomZ)), 5); } for (Entity entity : Client.mc.theWorld.loadedEntityList) { if (entity instanceof EntityFishHook && ((EntityFishHook) entity).angler == Client.mc.thePlayer) { fishingHook = entity; } } if (fishingHook == null) { currentStep = FishingSteps.FIND_ROD; return; } if (fishingMarker != null && fishingMarker.isEntityAlive() && fishingMarker.getName().contains("!!!")) { currentStep = FishingSteps.CATCH; fishingMarker = null; return; } return; } case CATCH: { KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode()); if (Config.AutoKill) { currentStep = FishingSteps.KILL_DELAY; } else { currentStep = FishingSteps.FIND_ROD; } catches++; } case KILL_DELAY: { if (MainCounter.countUntil(Config.KillDelay)) { return; } currentStep = FishingSteps.KILL_MONSTER; } case KILL_MONSTER: { if (fishingMonster == null || !fishingMonster.isEntityAlive() || !Client.mc.thePlayer.canEntityBeSeen(fishingMonster)) { currentStep = FishingSteps.FIND_ROD; fishingMonster = null; return; } Client.mc.thePlayer.inventory.currentItem = Config.WeaponSlot - 1; AxisAlignedBB boundingBox = fishingMonster.getEntityBoundingBox(); double deltaX = boundingBox.maxX - boundingBox.minX; double deltaY = boundingBox.maxY - boundingBox.minY; double deltaZ = boundingBox.maxZ - boundingBox.minZ; BlockPos randomPositionOnBoundingBox = new BlockPos(boundingBox.minX + deltaX, boundingBox.minY + deltaY, boundingBox.minZ + deltaZ); Client.rotation.setYaw(Math.getYaw(randomPositionOnBoundingBox), Config.RotationSmoothing); Client.rotation.setPitch(Math.getPitch(randomPositionOnBoundingBox), Config.RotationSmoothing); if (!MainCounter.countUntil(20 / Config.AttackCps)) { MainCounter.add(java.lang.Math.random() * 100 > 70 ? 1 : 0); if (Config.RightClick) { KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode()); return; } KeyBinding.onTick(Client.mc.gameSettings.keyBindAttack.getKeyCode()); } } } } @SubscribeEvent public void renderWorld(RenderWorldLastEvent event) { if (lastAABB != null) { Render.drawOutlinedFilledBoundingBox(lastAABB, Config.VisualColor.toJavaColor(), event.partialTicks); } } @SubscribeEvent public void entitySpawn(EntityJoinWorldEvent event) { if (fishingHook == null || event.entity instanceof EntitySquid || event.entity.getName().equals("item.tile.stone.stone")) { return; } if (event.entity instanceof EntityArmorStand && event.entity.getDistanceToEntity(fishingHook) <= 0.1) { fishingMarker = event.entity; return; } if (fishingMonster == null && event.entity.getDistanceToEntity(fishingHook) <= 1.5 ) { fishingMonster = event.entity; } } @SubscribeEvent public void chatReceive(ClientChatReceivedEvent event) { if (event.type != 2) { return; } Matcher matcher = Regex.FishingSkillPattern.matcher(event.message.getFormattedText()); if (matcher.find()) { xpGain += Float.parseFloat(matcher.group(1)); } } @SubscribeEvent
public void packetReceive(PacketEvent.ReceiveEvent event) {
1
2023-11-16 10:12:20+00:00
8k
maarlakes/common
src/main/java/cn/maarlakes/common/factory/datetime/DateTimeFactories.java
[ { "identifier": "Ordered", "path": "src/main/java/cn/maarlakes/common/Ordered.java", "snippet": "public interface Ordered {\n\n int HIGHEST = Integer.MIN_VALUE;\n\n int LOWEST = Integer.MAX_VALUE;\n\n int order();\n}" }, { "identifier": "OrderedComparator", "path": "src/main/java/cn/maarlakes/common/OrderedComparator.java", "snippet": "public class OrderedComparator implements Comparator<Object> {\n\n protected OrderedComparator() {\n }\n\n @Nonnull\n public static OrderedComparator getInstance() {\n return Helper.COMPARATOR;\n }\n\n @Override\n public int compare(Object obj1, Object obj2) {\n if (obj1 == obj2) {\n return 0;\n }\n return Integer.compare(getOrder(obj1), getOrder(obj2));\n }\n\n protected int getOrder(Object obj) {\n if (obj == null) {\n return Ordered.LOWEST;\n }\n final Integer order = findOrder(obj);\n return order == null ? Ordered.LOWEST : order;\n }\n\n protected Integer findOrder(@Nonnull Object obj) {\n if (obj instanceof Ordered) {\n return ((Ordered) obj).order();\n }\n return null;\n }\n\n private static final class Helper {\n static final OrderedComparator COMPARATOR = new OrderedComparator();\n }\n}" }, { "identifier": "SpiServiceLoader", "path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java", "snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader, ConcurrentMap<Class<?>, SpiServiceLoader<?>>> SERVICE_LOADER_CACHE = new ConcurrentHashMap<>();\n\n private final Class<T> service;\n\n private final ClassLoader loader;\n private final boolean isShared;\n\n private final Supplier<List<Holder>> holders = Lazy.of(this::loadServiceHolder);\n private final ConcurrentMap<Class<?>, T> serviceCache = new ConcurrentHashMap<>();\n\n private SpiServiceLoader(@Nonnull Class<T> service, ClassLoader loader, boolean isShared) {\n this.service = Objects.requireNonNull(service, \"Service interface cannot be null\");\n this.loader = (loader == null) ? service.getClassLoader() : loader;\n this.isShared = isShared;\n }\n\n public boolean isEmpty() {\n return this.holders.get().isEmpty();\n }\n\n @Nonnull\n public T first() {\n return this.firstOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public T first(@Nonnull Class<? extends T> serviceType) {\n return this.firstOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> firstOptional() {\n return this.firstOptional(this.service);\n }\n\n @Nonnull\n public Optional<T> firstOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream().filter(item -> serviceType.isAssignableFrom(item.serviceType)).map(this::loadService).findFirst();\n }\n\n @Nonnull\n public T last() {\n return this.lastOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional() {\n return this.lastOptional(this.service);\n }\n\n @Nonnull\n public T last(@Nonnull Class<? extends T> serviceType) {\n return this.lastOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream()\n .filter(item -> serviceType.isAssignableFrom(item.serviceType))\n .sorted((left, right) -> Holder.compare(right, left))\n .map(this::loadService)\n .findFirst();\n }\n\n @Nonnull\n @Override\n public Iterator<T> iterator() {\n return this.holders.get().stream().map(this::loadService).iterator();\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service) {\n return load(service, Thread.currentThread().getContextClassLoader());\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service, ClassLoader loader) {\n return new SpiServiceLoader<>(service, loader, false);\n }\n\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service) {\n return loadShared(service, Thread.currentThread().getContextClassLoader());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service, ClassLoader loader) {\n final ClassLoader cl = loader == null ? ClassLoader.getSystemClassLoader() : loader;\n return (SpiServiceLoader<S>) SERVICE_LOADER_CACHE.computeIfAbsent(cl, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(service, k -> new SpiServiceLoader<>(service, cl, true));\n }\n\n private T loadService(@Nonnull Holder holder) {\n if (holder.spiService != null && holder.spiService.lifecycle() == SpiService.Lifecycle.SINGLETON) {\n return this.serviceCache.computeIfAbsent(holder.serviceType, k -> this.createService(holder));\n }\n return this.createService(holder);\n }\n\n private T createService(@Nonnull Holder holder) {\n try {\n return this.service.cast(holder.serviceType.getConstructor().newInstance());\n } catch (Exception e) {\n throw new SpiServiceException(e.getMessage(), e);\n }\n }\n\n\n private List<Holder> loadServiceHolder() {\n final Enumeration<URL> configs = this.loadConfigs();\n try {\n final Map<String, Holder> map = new HashMap<>();\n while (configs.hasMoreElements()) {\n final URL url = configs.nextElement();\n try (InputStream in = url.openStream()) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {\n String ln;\n int lineNumber = 0;\n while ((ln = reader.readLine()) != null) {\n lineNumber++;\n final int ci = ln.indexOf('#');\n if (ci >= 0) {\n ln = ln.substring(0, ci);\n }\n ln = ln.trim();\n if (!ln.isEmpty()) {\n this.check(url, ln, lineNumber);\n if (!map.containsKey(ln)) {\n final Class<?> type = Class.forName(ln, false, loader);\n if (!this.service.isAssignableFrom(type)) {\n throw new SpiServiceException(this.service.getName() + \": Provider\" + ln + \" not a subtype\");\n }\n map.put(ln, new Holder(type, type.getAnnotation(SpiService.class)));\n }\n }\n }\n }\n }\n }\n if (map.isEmpty() && this.isShared) {\n // 移除\n this.remove();\n }\n\n return map.values().stream().sorted().collect(Collectors.toList());\n } catch (IOException | ClassNotFoundException e) {\n if (this.isShared) {\n this.remove();\n }\n throw new SpiServiceException(e);\n }\n }\n\n private void remove() {\n final ConcurrentMap<Class<?>, SpiServiceLoader<?>> map = SERVICE_LOADER_CACHE.get(this.loader);\n if (map != null) {\n map.remove(this.service);\n }\n }\n\n private Enumeration<URL> loadConfigs() {\n final String fullName = PREFIX + service.getName();\n try {\n return this.loader.getResources(fullName);\n } catch (IOException e) {\n throw new SpiServiceException(service.getName() + \": Error locating configuration files\", e);\n }\n }\n\n private void check(@Nonnull URL url, @Nonnull String className, int lineNumber) {\n if ((className.indexOf(' ') >= 0) || (className.indexOf('\\t') >= 0)) {\n throw new SpiServiceException(this.service.getName() + \": \" + className + \":\" + lineNumber + \":Illegal configuration-file syntax\");\n }\n int cp = className.codePointAt(0);\n if (!Character.isJavaIdentifierStart(cp)) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n final int length = className.length();\n for (int i = Character.charCount(cp); i < length; i += Character.charCount(cp)) {\n cp = className.codePointAt(i);\n if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n }\n }\n\n private static final class Holder implements Comparable<Holder> {\n\n private final Class<?> serviceType;\n\n private final SpiService spiService;\n\n private Holder(@Nonnull Class<?> serviceType, SpiService spiService) {\n this.serviceType = serviceType;\n this.spiService = spiService;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof Holder) {\n return this.serviceType == ((Holder) obj).serviceType;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(serviceType);\n }\n\n @Override\n public int compareTo(@Nullable Holder o) {\n if (o == null) {\n return 1;\n }\n return Integer.compare(this.spiService == null ? Integer.MAX_VALUE : this.spiService.order(), o.spiService == null ? Integer.MAX_VALUE : o.spiService.order());\n }\n\n public static int compare(Holder left, Holder right) {\n if (left == right) {\n return 0;\n }\n if (left == null) {\n return -1;\n }\n return left.compareTo(right);\n }\n }\n}" }, { "identifier": "Comparators", "path": "src/main/java/cn/maarlakes/common/utils/Comparators.java", "snippet": "public final class Comparators {\n private Comparators() {\n }\n\n @SafeVarargs\n public static <T extends Comparable<? super T>> T min(@Nonnull T... array) {\n return minOptional(array).orElse(null);\n }\n\n @Nonnull\n @SafeVarargs\n public static <T extends Comparable<? super T>> Optional<T> minOptional(@Nonnull T... array) {\n return minOptional(array, Comparator.naturalOrder());\n }\n\n @SafeVarargs\n public static <T> T min(@Nonnull Comparator<? super T> comparator, @Nonnull T... array) {\n return min(array, comparator);\n }\n\n @Nonnull\n @SafeVarargs\n public static <T> Optional<T> minOptional(@Nonnull Comparator<? super T> comparator, @Nonnull T... array) {\n return minOptional(array, comparator);\n }\n\n public static <T> T min(@Nonnull T[] array, @Nonnull Comparator<? super T> comparator) {\n return minOptional(array, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> minOptional(@Nonnull T[] array, @Nonnull Comparator<? super T> comparator) {\n return Arrays.stream(array).min(comparator);\n }\n\n @SafeVarargs\n public static <T extends Comparable<? super T>> T max(@Nonnull T... array) {\n return maxOptional(array, Comparator.naturalOrder()).orElse(null);\n }\n\n @Nonnull\n @SafeVarargs\n public static <T extends Comparable<? super T>> Optional<T> maxOptional(@Nonnull T... array) {\n return maxOptional(array, Comparator.naturalOrder());\n }\n\n @SafeVarargs\n public static <T> T max(@Nonnull Comparator<? super T> comparator, @Nonnull T... array) {\n return maxOptional(array, comparator).orElse(null);\n }\n\n @Nonnull\n @SafeVarargs\n public static <T> Optional<T> maxOptional(@Nonnull Comparator<? super T> comparator, @Nonnull T... array) {\n return maxOptional(array, comparator);\n }\n\n public static <T> T max(@Nonnull T[] array, @Nonnull Comparator<? super T> comparator) {\n return maxOptional(array, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> maxOptional(@Nonnull T[] array, @Nonnull Comparator<? super T> comparator) {\n return Arrays.stream(array).max(comparator);\n }\n\n public static <T> T min(Iterable<T> list, @Nonnull Comparator<? super T> comparator) {\n return minOptional(list, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> minOptional(Iterable<T> list, @Nonnull Comparator<? super T> comparator) {\n if (list instanceof Collection) {\n return ((Collection<T>) list).stream().min(comparator);\n }\n return StreamSupport.stream(list.spliterator(), false).min(comparator);\n }\n\n public static <T> T max(@Nonnull Iterable<T> list, @Nonnull Comparator<? super T> comparator) {\n return maxOptional(list, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> maxOptional(Iterable<T> list, Comparator<? super T> comparator) {\n if (list instanceof Collection) {\n return ((Collection<T>) list).stream().max(comparator);\n }\n return StreamSupport.stream(list.spliterator(), false).max(comparator);\n }\n\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n public static <T extends Comparable<? super T>> T min(@Nonnull Iterable<T> list) {\n return (T) minOptional((Iterable) list).orElse(null);\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> Optional<T> minOptional(@Nonnull Iterable<T> list) {\n return minOptional(list, Comparator.naturalOrder());\n }\n\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n public static <T extends Comparable<? super T>> T max(@Nonnull Iterable<T> list) {\n return (T) maxOptional((Iterable) list).orElse(null);\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> Optional<T> maxOptional(@Nonnull Iterable<T> list) {\n return maxOptional(list, Comparator.naturalOrder());\n }\n\n public static <T extends Comparable<? super T>> T min(@Nonnull Iterator<T> iterator) {\n return minOptional(iterator).orElse(null);\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> Optional<T> minOptional(@Nonnull Iterator<T> iterator) {\n return minOptional(iterator, Comparator.naturalOrder());\n }\n\n public static <T> T min(@Nonnull Iterator<T> iterator, Comparator<? super T> comparator) {\n return minOptional(iterator, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> minOptional(@Nonnull Iterator<T> iterator, @Nonnull Comparator<? super T> comparator) {\n T min = null;\n while (iterator.hasNext()) {\n final T next = iterator.next();\n if (min == null) {\n min = next;\n } else {\n if (comparator.compare(min, next) > 0) {\n min = next;\n }\n }\n }\n return Optional.ofNullable(min);\n }\n\n public static <T extends Comparable<? super T>> T max(@Nonnull Iterator<T> iterator) {\n return maxOptional(iterator).orElse(null);\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> Optional<T> maxOptional(@Nonnull Iterator<T> iterator) {\n return maxOptional(iterator, Comparator.naturalOrder());\n }\n\n public static <T> T max(@Nonnull Iterator<T> iterator, @Nonnull Comparator<? super T> comparator) {\n return maxOptional(iterator, comparator).orElse(null);\n }\n\n @Nonnull\n public static <T> Optional<T> maxOptional(@Nonnull Iterator<T> iterator, @Nonnull Comparator<? super T> comparator) {\n T max = null;\n while (iterator.hasNext()) {\n final T next = iterator.next();\n if (max == null) {\n max = next;\n } else {\n if (comparator.compare(max, next) < 0) {\n max = next;\n }\n }\n }\n return Optional.ofNullable(max);\n }\n}" }, { "identifier": "Lazy", "path": "src/main/java/cn/maarlakes/common/utils/Lazy.java", "snippet": "public interface Lazy<T> extends Supplier<T> {\n\n boolean isCreated();\n\n @Nonnull\n static <T> Lazy<T> of(@Nonnull Supplier<T> factory) {\n if (factory instanceof Lazy) {\n return (Lazy<T>) factory;\n }\n return new DefaultLazy<>(factory);\n }\n}" } ]
import cn.maarlakes.common.Ordered; import cn.maarlakes.common.OrderedComparator; import cn.maarlakes.common.spi.SpiServiceLoader; import cn.maarlakes.common.utils.Comparators; import cn.maarlakes.common.utils.Lazy; import jakarta.annotation.Nonnull; import java.time.*; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.chrono.ChronoZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.time.temporal.ChronoField.*;
6,565
@Nonnull public static LocalDateTime fromEpochMilli(long epocMilli, @Nonnull ZoneId zone) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(epocMilli), zone); } public static long toEpochSecond(@Nonnull LocalDateTime dateTime) { return toEpochSecond(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime)); } public static long toEpochSecond(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) { return toEpochMilli(dateTime, offset) / 1000; } public static long toEpochMilli(@Nonnull LocalDateTime dateTime) { return toEpochMilli(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime)); } public static long toEpochMilli(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) { return dateTime.toInstant(offset).toEpochMilli(); } private static LocalDateTime toLocalDateTime(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalDateTime) { return (LocalDateTime) accessor; } if (accessor instanceof ZonedDateTime) { return ((ZonedDateTime) accessor).toLocalDateTime(); } if (accessor instanceof OffsetDateTime) { return ((OffsetDateTime) accessor).toLocalDateTime(); } if (accessor instanceof LocalDate) { return LocalDateTime.of((LocalDate) accessor, LocalTime.MIN); } if (accessor instanceof LocalTime) { return LocalDateTime.of(LocalDate.now(), (LocalTime) accessor); } if (accessor instanceof OffsetTime) { return LocalDateTime.of(LocalDate.now(), ((OffsetTime) accessor).toLocalTime()); } if (accessor instanceof Instant) { final Instant instant = (Instant) accessor; return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } final LocalDate date = tryToLocalDate(accessor); final LocalTime time = tryToLocalTime(accessor); if (date != null) { if (time == null) { return LocalDateTime.of(date, LocalTime.MIDNIGHT); } return LocalDateTime.of(date, time); } if (time != null) { return LocalDateTime.of(LocalDate.now(), time); } return LocalDateTime.from(accessor); } private static LocalDate tryToLocalDate(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalDate) { return (LocalDate) accessor; } if (accessor.isSupported(EPOCH_DAY)) { return LocalDate.ofEpochDay(accessor.getLong(EPOCH_DAY)); } if (!accessor.isSupported(YEAR)) { if (!accessor.isSupported(MONTH_OF_YEAR)) { return null; } final int month = accessor.get(MONTH_OF_YEAR); final LocalDate now = LocalDate.now(); if (!accessor.isSupported(DAY_OF_MONTH)) { return LocalDate.of(now.getYear(), month, 1); } return LocalDate.of(now.getYear(), month, accessor.get(DAY_OF_MONTH)); } if (!accessor.isSupported(MONTH_OF_YEAR)) { return LocalDate.of(accessor.get(YEAR), 1, 1); } if (!accessor.isSupported(DAY_OF_MONTH)) { return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), 1); } return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), accessor.get(DAY_OF_MONTH)); } private static LocalTime tryToLocalTime(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalTime) { return (LocalTime) accessor; } if (accessor instanceof OffsetTime) { return ((OffsetTime) accessor).toLocalTime(); } final LocalTime time = accessor.query(TemporalQueries.localTime()); if (time != null) { return time; } if (accessor.isSupported(SECOND_OF_DAY)) { return LocalTime.ofSecondOfDay(accessor.getLong(SECOND_OF_DAY)); } if (!accessor.isSupported(HOUR_OF_DAY)) { return null; } final int hour = accessor.get(HOUR_OF_DAY); if (!accessor.isSupported(MINUTE_OF_HOUR)) { return LocalTime.of(hour, 0); } final int minute = accessor.get(MINUTE_OF_HOUR); if (!accessor.isSupported(SECOND_OF_MINUTE)) { return LocalTime.of(hour, minute); } final int second = accessor.get(SECOND_OF_MINUTE); if (!accessor.isSupported(NANO_OF_SECOND)) { return LocalTime.of(hour, minute, second); } return LocalTime.of(hour, minute, second, accessor.get(NANO_OF_SECOND)); }
package cn.maarlakes.common.factory.datetime; /** * @author linjpxc */ public final class DateTimeFactories { private DateTimeFactories() { } private static final Supplier<List<ParserWrapper>> PARSER = Lazy.of(() -> StreamSupport.stream(SpiServiceLoader.loadShared(DateTimeParser.class, DateTimeParser.class.getClassLoader()).spliterator(), false) .map(ParserWrapper::new) .collect(Collectors.toList()) ); private static final Comparator<Object> COMPARATOR = OrderedComparator.getInstance().reversed(); public static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendValue(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .appendValue(MINUTE_OF_HOUR, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .optionalStart() .appendValue(SECOND_OF_MINUTE, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, true) .optionalEnd() .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, false) .optionalEnd() .optionalStart() .appendOffsetId() .toFormatter(); public static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .optionalStart() .appendValueReduced(YEAR_OF_ERA, 2, 4, LocalDate.of(2000, 1, 1)) .optionalEnd() .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('年') .optionalEnd() .appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('月') .optionalEnd() .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('日') .optionalEnd() .toFormatter(); public static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DATE_FORMATTER) .optionalStart() .appendLiteral(' ') .optionalEnd() .optionalStart() .appendLiteral('T') .optionalEnd() .optionalStart() .append(TIME_FORMATTER) .optionalEnd() .toFormatter(); @Nonnull public static LocalDateTime parse(@Nonnull String datetime) { return parse(datetime, Locale.getDefault(Locale.Category.FORMAT)); } @Nonnull public static LocalDateTime parse(@Nonnull String datetime, @Nonnull Locale locale) { final String newDatetime = datetime.trim(); return PARSER.get().stream().sorted(COMPARATOR) .filter(item -> item.parser.supported(newDatetime, LocalDateTime.class, locale)) .findFirst() .map(item -> { final LocalDateTime time = toLocalDateTime(item.parser.parse(newDatetime, locale)); item.counter.incrementAndGet(); return time; }).orElseGet(() -> LocalDateTime.parse(newDatetime, DATE_TIME_FORMATTER.withLocale(locale))); } @Nonnull @SafeVarargs public static <T extends ChronoLocalDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) { final T min = Comparators.min(others); if (min != null && first.compareTo(min) > 0) { return min; } return first; } @Nonnull @SafeVarargs public static <T extends ChronoLocalDateTime<?>> T max(@Nonnull T first, @Nonnull T... others) { final T max = Comparators.max(others); if (max != null && first.compareTo(max) < 0) { return max; } return first; } @Nonnull @SafeVarargs public static <T extends ChronoLocalDate> T min(@Nonnull T first, @Nonnull T... others) { final T min = Comparators.min(others); if (min != null && first.compareTo(min) > 0) { return min; } return first; } @Nonnull @SafeVarargs public static <T extends ChronoLocalDate> T max(@Nonnull T first, @Nonnull T... others) { final T max = Comparators.max(others); if (max != null && first.compareTo(max) < 0) { return max; } return first; } @Nonnull @SafeVarargs public static <T extends ChronoZonedDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) { final T min = Comparators.min(others); if (min != null && first.compareTo(min) > 0) { return min; } return first; } @Nonnull @SafeVarargs public static <T extends ChronoZonedDateTime<?>> T max(@Nonnull T first, @Nonnull T... others) { final T max = Comparators.max(others); if (max != null && first.compareTo(max) < 0) { return max; } return first; } @Nonnull public static LocalTime min(@Nonnull LocalTime first, @Nonnull LocalTime... others) { final LocalTime min = Comparators.min(others); if (min != null && first.isAfter(min)) { return min; } return first; } @Nonnull public static LocalTime max(@Nonnull LocalTime first, @Nonnull LocalTime... others) { final LocalTime max = Comparators.max(others); if (max != null && first.isBefore(max)) { return max; } return first; } @Nonnull public static Instant min(@Nonnull Instant first, @Nonnull Instant... others) { final Instant min = Comparators.min(others); if (min != null && first.isAfter(min)) { return min; } return first; } @Nonnull public static Instant max(@Nonnull Instant first, @Nonnull Instant... others) { final Instant max = Comparators.max(others); if (max != null && first.isBefore(max)) { return max; } return first; } @Nonnull public static OffsetDateTime min(@Nonnull OffsetDateTime first, @Nonnull OffsetDateTime... others) { final OffsetDateTime min = Comparators.min(others); if (min != null && first.isAfter(min)) { return min; } return first; } @Nonnull public static OffsetDateTime max(@Nonnull OffsetDateTime first, @Nonnull OffsetDateTime... others) { final OffsetDateTime max = Comparators.max(others); if (max != null && first.isBefore(max)) { return max; } return first; } @Nonnull public static OffsetTime min(@Nonnull OffsetTime first, @Nonnull OffsetTime... others) { final OffsetTime min = Comparators.min(others); if (min != null && first.isAfter(min)) { return min; } return first; } @Nonnull public static OffsetTime max(@Nonnull OffsetTime first, @Nonnull OffsetTime... others) { final OffsetTime max = Comparators.max(others); if (max != null && first.isBefore(max)) { return max; } return first; } @Nonnull public static LocalDateTime parse(@Nonnull String datetime, @Nonnull String pattern) { return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern(pattern)); } @Nonnull public static LocalDateTime fromEpochSecond(long epochSecond) { return fromEpochSecond(epochSecond, ZoneId.systemDefault()); } @Nonnull public static LocalDateTime fromEpochSecond(long epochSecond, @Nonnull ZoneId zone) { return LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), zone); } @Nonnull public static LocalDateTime fromEpochSecond(long epochSecond, long nanoAdjustment) { return fromEpochSecond(epochSecond, nanoAdjustment, ZoneId.systemDefault()); } @Nonnull public static LocalDateTime fromEpochSecond(long epochSecond, long nanoAdjustment, @Nonnull ZoneId zone) { return LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond, nanoAdjustment), zone); } @Nonnull public static LocalDateTime fromEpochMilli(long epocMilli) { return fromEpochMilli(epocMilli, ZoneId.systemDefault()); } @Nonnull public static LocalDateTime fromEpochMilli(long epocMilli, @Nonnull ZoneId zone) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(epocMilli), zone); } public static long toEpochSecond(@Nonnull LocalDateTime dateTime) { return toEpochSecond(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime)); } public static long toEpochSecond(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) { return toEpochMilli(dateTime, offset) / 1000; } public static long toEpochMilli(@Nonnull LocalDateTime dateTime) { return toEpochMilli(dateTime, ZoneOffset.systemDefault().getRules().getOffset(dateTime)); } public static long toEpochMilli(@Nonnull LocalDateTime dateTime, @Nonnull ZoneOffset offset) { return dateTime.toInstant(offset).toEpochMilli(); } private static LocalDateTime toLocalDateTime(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalDateTime) { return (LocalDateTime) accessor; } if (accessor instanceof ZonedDateTime) { return ((ZonedDateTime) accessor).toLocalDateTime(); } if (accessor instanceof OffsetDateTime) { return ((OffsetDateTime) accessor).toLocalDateTime(); } if (accessor instanceof LocalDate) { return LocalDateTime.of((LocalDate) accessor, LocalTime.MIN); } if (accessor instanceof LocalTime) { return LocalDateTime.of(LocalDate.now(), (LocalTime) accessor); } if (accessor instanceof OffsetTime) { return LocalDateTime.of(LocalDate.now(), ((OffsetTime) accessor).toLocalTime()); } if (accessor instanceof Instant) { final Instant instant = (Instant) accessor; return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } final LocalDate date = tryToLocalDate(accessor); final LocalTime time = tryToLocalTime(accessor); if (date != null) { if (time == null) { return LocalDateTime.of(date, LocalTime.MIDNIGHT); } return LocalDateTime.of(date, time); } if (time != null) { return LocalDateTime.of(LocalDate.now(), time); } return LocalDateTime.from(accessor); } private static LocalDate tryToLocalDate(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalDate) { return (LocalDate) accessor; } if (accessor.isSupported(EPOCH_DAY)) { return LocalDate.ofEpochDay(accessor.getLong(EPOCH_DAY)); } if (!accessor.isSupported(YEAR)) { if (!accessor.isSupported(MONTH_OF_YEAR)) { return null; } final int month = accessor.get(MONTH_OF_YEAR); final LocalDate now = LocalDate.now(); if (!accessor.isSupported(DAY_OF_MONTH)) { return LocalDate.of(now.getYear(), month, 1); } return LocalDate.of(now.getYear(), month, accessor.get(DAY_OF_MONTH)); } if (!accessor.isSupported(MONTH_OF_YEAR)) { return LocalDate.of(accessor.get(YEAR), 1, 1); } if (!accessor.isSupported(DAY_OF_MONTH)) { return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), 1); } return LocalDate.of(accessor.get(YEAR), accessor.get(MONTH_OF_YEAR), accessor.get(DAY_OF_MONTH)); } private static LocalTime tryToLocalTime(@Nonnull TemporalAccessor accessor) { if (accessor instanceof LocalTime) { return (LocalTime) accessor; } if (accessor instanceof OffsetTime) { return ((OffsetTime) accessor).toLocalTime(); } final LocalTime time = accessor.query(TemporalQueries.localTime()); if (time != null) { return time; } if (accessor.isSupported(SECOND_OF_DAY)) { return LocalTime.ofSecondOfDay(accessor.getLong(SECOND_OF_DAY)); } if (!accessor.isSupported(HOUR_OF_DAY)) { return null; } final int hour = accessor.get(HOUR_OF_DAY); if (!accessor.isSupported(MINUTE_OF_HOUR)) { return LocalTime.of(hour, 0); } final int minute = accessor.get(MINUTE_OF_HOUR); if (!accessor.isSupported(SECOND_OF_MINUTE)) { return LocalTime.of(hour, minute); } final int second = accessor.get(SECOND_OF_MINUTE); if (!accessor.isSupported(NANO_OF_SECOND)) { return LocalTime.of(hour, minute, second); } return LocalTime.of(hour, minute, second, accessor.get(NANO_OF_SECOND)); }
private static final class ParserWrapper implements Ordered {
0
2023-11-18 07:49:00+00:00
8k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/cashierController.java
[ { "identifier": "App", "path": "src/main/java/com/systeminventory/App.java", "snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException{\n primaryStage = stage;\n loadLoginScene();\n\n }\n\n public static Stage getPrimaryStage(){\n return primaryStage;\n }\n\n public static void loadLoginScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setResizable(false);\n primaryStage.initStyle(StageStyle.UNDECORATED);\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadLogoutScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"dashboardLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadProductScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"productLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Product - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"cashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Cashier - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n\n }\n public static void loadEmployeeDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeProductLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadEmployeeCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeCashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n}" }, { "identifier": "Cashier", "path": "src/main/java/com/systeminventory/model/Cashier.java", "snippet": "public class Cashier {\n\n private String cashierName;\n private String cashierNoPhone;\n private String cashierImageSource;\n private String cashierEmail;\n private String cashierPassword;\n private String cashierDateOfBirth;\n private String cashierAddress;\n\n private String keyCashier;\n\n public String getCashierName() {\n return cashierName;\n }\n\n public void setCashierName(String cashierName) {\n this.cashierName = cashierName;\n }\n\n public String getCashierNoPhone() {\n return cashierNoPhone;\n }\n\n public void setCashierNoPhone(String cashierNoPhone) {\n this.cashierNoPhone = cashierNoPhone;\n }\n\n public String getCashierImageSource() {\n return cashierImageSource;\n }\n\n public void setCashierImageSource(String cashierImageSource) {\n this.cashierImageSource = cashierImageSource;\n }\n\n public String getCashierEmail() {\n return cashierEmail;\n }\n\n public void setCashierEmail(String cashierEmail) {\n this.cashierEmail = cashierEmail;\n }\n\n public String getCashierPassword() {\n return cashierPassword;\n }\n\n public void setCashierPassword(String cashierPassword) {\n this.cashierPassword = cashierPassword;\n }\n\n public String getCashierDateOfBirth() {\n return cashierDateOfBirth;\n }\n\n public void setCashierDateOfBirth(String cashierDateOfBirth) {\n this.cashierDateOfBirth = cashierDateOfBirth;\n }\n\n public String getCashierAddress() {\n return cashierAddress;\n }\n\n public void setCashierAddress(String cashierAddress) {\n this.cashierAddress = cashierAddress;\n }\n\n public String getKeyCashier() {\n return keyCashier;\n }\n\n public void setKeyCashier(String keyCashier) {\n this.keyCashier = keyCashier;\n }\n}" }, { "identifier": "Product", "path": "src/main/java/com/systeminventory/model/Product.java", "snippet": "public class Product {\n private String productName;\n private String imageSource;\n private String productOriginalPrice;\n private String productSellingPrice;\n private String productStock;\n private String keyProduct;\n private String idProduct;\n\n\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getImageSource() {\n return imageSource;\n }\n\n public void setImageSource(String imageSource) {\n this.imageSource = imageSource;\n }\n\n public String getProductSellingPrice() {\n return productSellingPrice;\n }\n\n public void setProductSellingPrice(String productSellingPrice) {\n this.productSellingPrice = productSellingPrice;\n }\n\n public String getProductStock() {\n return productStock;\n }\n\n public void setProductStock(String productStock) {\n this.productStock = productStock;\n }\n\n public String getKeyProduct() {\n return keyProduct;\n }\n\n public void setKeyProduct(String keyProduct) {\n this.keyProduct = keyProduct;\n }\n\n public String getProductOriginalPrice() {\n return productOriginalPrice;\n }\n\n public void setProductOriginalPrice(String productOriginalPrice) {\n this.productOriginalPrice = productOriginalPrice;\n }\n\n public String getIdProduct() {\n return idProduct;\n }\n\n public void setIdProduct(String idProduct) {\n this.idProduct = idProduct;\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.systeminventory.App; import com.systeminventory.interfaces.*; import com.systeminventory.model.Cashier; import com.systeminventory.model.Product; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List;
4,312
} if (status == 0){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (InputStream inputStream = new FileInputStream(jsonPath)) { InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); JsonObject profileKey = jsonObject.getAsJsonObject(keyProfileOnPopup.getText()); if (keyProfileOnPopup != null){ String imageFileName = addProfileProfileImagePathLabel.getText(); if(!(imageProfilePath+imageFileName).equals(profileKey.get("Image").getAsString())){ Path newSourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText()); Path targetImagePath = Paths.get(imageProfilePath, imageFileName); try { Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException err){ err.printStackTrace(); } } profileKey.addProperty("Name", addProfileNameField.getText()); profileKey.addProperty("Email", addProfileEmailField.getText()); profileKey.addProperty("Phone", addProfileNoPhoneField.getText()); profileKey.addProperty("DateOfBirth", addProfileDateOfBirthField.getText()); profileKey.addProperty("Address", addProfileAddressField.getText()); profileKey.addProperty("Image", imageProfilePath+imageFileName); profileKey.addProperty("Password", profileKey.get("Password").getAsString()); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } } } catch (IOException err){ err.printStackTrace(); } } App.loadCashierScene(); } } @FXML private void onAddProfileApplyButtonMouseEnter(MouseEvent mouseEvent) { addProfileApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileApplyButtonMouseExit(MouseEvent mouseEvent) { addProfileApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileCancelButtonClick(ActionEvent actionEvent) { backgroundPopup.setVisible(false); addProfilePopup.setVisible(false); } @FXML private void onAddProfileCancelButtonMouseEnter(MouseEvent mouseEvent) { addProfileCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileCancelButtonMouseExit(MouseEvent mouseEvent) { addProfileCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13"); } public void deleteProfileData(String keyProfile){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json"; try (InputStream inputStream = new FileInputStream(jsonPath)){ InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); jsonObject.remove(keyProfile); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } App.loadCashierScene(); } catch (IOException err){ err.printStackTrace(); } } @FXML private void onConfirmDeleteDeleteButtonProfileClick(ActionEvent event) { deleteProfileData(confirmDeleteKeyProfile.getText()); confirmDeleteVariableProfileName.setText(""); confirmDeleteKeyProfile.setText(""); confirmDeleteProfilePane.setVisible(false); backgroundPopup.setVisible(false); } @FXML private void onConfirmDeleteDeleteButtonProfileMouseEnter(MouseEvent event) { confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #e0005c;"+"-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteDeleteButtonProfileMouseExit(MouseEvent event) { confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #ff1474;"+"-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileMouseEnter(MouseEvent event) { confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #19a6b7;" + "-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileMouseExit(MouseEvent mouseEvent) { confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #1ecbe1;" + "-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileClick(ActionEvent event) { backgroundPopup.setVisible(false); confirmDeleteProfilePane.setVisible(false); confirmDeleteKeyProfile.setText(""); confirmDeleteVariableProfileName.setText(""); }
package com.systeminventory.controller; public class cashierController { @FXML private Pane backgroundPopup; @FXML private Button buttonCashier; @FXML private Button buttonDashboard; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Pane addProfilePopup; @FXML private Label addProfileNameLabel; @FXML private TextField addProfileNameField; @FXML private Label addProfileEmailLabel; @FXML private TextField addProfileEmailField; @FXML private Label addProfileNoPhoneLabel; @FXML private TextField addProfileNoPhoneField; @FXML private Label addProfileDateOfBirthLabel; @FXML private TextField addProfileDateOfBirthField; @FXML private Label addProfileAddressLabel; @FXML private TextField addProfileAddressField; @FXML private Label addProfileProfilePictureLabel; @FXML private Label addProfileProfileImagePathLabel; @FXML private Button addProfileApplyButton; @FXML private Button addProfileCancelButton; @FXML private Label addProfileProfileImageFullPathLabel; @FXML private Button buttonAddProfile; @FXML private Pane addProfileChooseFilePane; @FXML private GridPane profileCardContainer; @FXML private Label profileDetailsVarFullName; @FXML private Label profileDetailsVarPhone; @FXML private Label profileDetailsVarDateOfBirth; @FXML private Label profileDetailsVarEmail; @FXML private Label profileDetailsVarAddress; @FXML public Pane paneSelectAProfile; private ProfileDetailsListener profileDetailsListener; private DeleteCashierListener deleteCashierListener; private EditCashierListener editCashierListener; @FXML private ImageView profileDetailsVarImage; @FXML private TextField searchTermProfile; @FXML private Pane confirmDeleteProfilePane; @FXML private Label confirmDeleteVariableProfileName; @FXML private Button confirmDeleteDeleteButtonProfile; @FXML private Button confirmDeleteCancelButtonProfile; @FXML private Label confirmDeleteKeyProfile; @FXML private Label keyProfileOnPopup; @FXML private Label addProfileLabel; private static String hashMD5(String input) { StringBuilder result = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); byte[] byteData = md.digest(); for (byte aByteData : byteData) { result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result.toString(); } @FXML void onAddProfileChooseFilePaneMouseClick(MouseEvent event) { FileChooser filechooser = new FileChooser(); filechooser.setTitle("Select profile picture"); filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png")); File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage()); if(selectedFile != null){ setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:"); addProfileProfileImagePathLabel.setText(selectedFile.getName()); addProfileProfileImageFullPathLabel.setText(selectedFile.getPath()); } } @FXML void onAddProfileChooseFilePaneMouseEnter(MouseEvent event) { addProfileChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML void onAddProfileChooseFilePaneMouseExit(MouseEvent event) { addProfileChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML private void onButtonAddProfileMouseExit(MouseEvent mouseEvent) { buttonAddProfile.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;"); } @FXML private void onButtonAddProfileMouseEnter(MouseEvent mouseEvent) { buttonAddProfile.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;"); } @FXML void onButtonDashboardClick(ActionEvent event) throws IOException { App.loadDashboardScene(); } @FXML private void onButtonDashboardMouseEnter(MouseEvent mouseEvent) { buttonDashboard.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML private void onButtonDashboardMouseExit(MouseEvent mouseEvent) { buttonDashboard.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML void onButtonProductClick(ActionEvent event) throws IOException { App.loadProductScene(); } @FXML void onButtonProductMouseEnter(MouseEvent event) { buttonProduct.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML void onButtonProductMouseExit(MouseEvent event) { buttonProduct.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML void onButtonCashierClick(ActionEvent event) { } @FXML void onCashierProductMouseEnter(MouseEvent event) { } @FXML void onCashierProductMouseExit(MouseEvent event) { } @FXML void onLogoutClick(ActionEvent event) throws IOException { App.loadLogoutScene(); } @FXML void onLogoutDropdownMouseEnter(MouseEvent event) { logoutDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11"); } @FXML void onLogoutDropdownMouseExit(MouseEvent event) { logoutDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11"); } @FXML void onProfileClick(MouseEvent event) { profileDropdown.setVisible(!profileDropdown.isVisible()); } @FXML void onProfileDropdownMouseExit(MouseEvent event) { profileDropdown.setVisible(false); } @FXML void onSettingsDropdownMouseEnter(MouseEvent event) { settingsDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11"); } @FXML void onSettingsDropdownMouseExit(MouseEvent event) { settingsDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11"); } private void setLabelPropertiesTextFillWhite(Label label, String text){ label.setText(text); label.setStyle("-fx-text-fill: #f6f6f6;"); } @FXML void onButtonAddProfileClick(ActionEvent event) { addProfileLabel.setText("Add Profile"); addProfileNameField.setText(""); addProfileNameField.setDisable(false); addProfileEmailField.setText(""); addProfileNoPhoneField.setText(""); addProfileDateOfBirthField.setText(""); addProfileAddressField.setText(""); addProfileProfileImagePathLabel.setText(""); setLabelPropertiesTextFillWhite(addProfileNameLabel, "Name:"); setLabelPropertiesTextFillWhite(addProfileEmailLabel, "Email:"); setLabelPropertiesTextFillWhite(addProfileNoPhoneLabel, "No phone:"); setLabelPropertiesTextFillWhite(addProfileDateOfBirthLabel, "Date of birth:"); setLabelPropertiesTextFillWhite(addProfileAddressLabel, "Address:"); setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:"); backgroundPopup.setVisible(true); addProfilePopup.setVisible(true); } @FXML private void onAddProfileApplyButtonClick(ActionEvent actionEvent) throws IOException { String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json"; String imageProfilePath = "./src/main/java/com/systeminventory/assets/imagesCashier/"; setLabelPropertiesTextFillWhite(addProfileNameLabel, "Name:"); setLabelPropertiesTextFillWhite(addProfileEmailLabel, "Email:"); setLabelPropertiesTextFillWhite(addProfileNoPhoneLabel, "No phone:"); setLabelPropertiesTextFillWhite(addProfileDateOfBirthLabel, "Date of birth:"); setLabelPropertiesTextFillWhite(addProfileAddressLabel, "Address:"); setLabelPropertiesTextFillWhite(addProfileProfilePictureLabel, "Profile picture:"); TextField[] fields = { addProfileNameField, addProfileEmailField, addProfileNoPhoneField, addProfileDateOfBirthField, addProfileAddressField }; Label[] labels = { addProfileNameLabel, addProfileEmailLabel, addProfileNoPhoneLabel, addProfileDateOfBirthLabel, addProfileAddressLabel }; if (addProfileLabel.getText().equals("Add Profile")){ // ADD PROFILE int status = 0; for (int i = 0; i < fields.length; i++){ TextField field = fields[i]; Label label = labels[i]; if (field.getText().isEmpty()){ label.setText(label.getText()+" (Required)"); label.setStyle("-fx-text-fill: #ff1474;"); status++; } } if (addProfileProfileImagePathLabel.getText().isEmpty()){ addProfileProfilePictureLabel.setText("Profile picture: (Required)"); addProfileProfilePictureLabel.setStyle("-fx-text-fill: #ff1474;"); status++; } if (status == 0){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (InputStream inputStream = new FileInputStream(jsonPath)){ InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); List<String> profileKeys = new ArrayList<>(jsonObject.keySet()); //Collections.sort(profileKeys); int nextKeyNumber = profileKeys.size()+1; String newProfileKey = "cashier"+nextKeyNumber; while (profileKeys.contains(newProfileKey)){ nextKeyNumber++; newProfileKey = "cashier"+nextKeyNumber; } JsonObject newProfileData = new JsonObject(); String imageFileName = addProfileProfileImagePathLabel.getText(); Path sourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText()); Path targetImagePath = Paths.get(imageProfilePath, imageFileName); newProfileData.addProperty("Name", addProfileNameField.getText()); newProfileData.addProperty("Email", addProfileEmailField.getText()); newProfileData.addProperty("Phone", addProfileNoPhoneField.getText()); newProfileData.addProperty("DateOfBirth", addProfileDateOfBirthField.getText()); newProfileData.addProperty("Address", addProfileAddressField.getText()); newProfileData.addProperty("Image", imageProfilePath+imageFileName); newProfileData.addProperty("Password", hashMD5("123456")); try{ Files.copy(sourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException err){ err.printStackTrace(); } jsonObject.add(newProfileKey, newProfileData); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } } catch (IOException err){ err.printStackTrace(); } App.loadCashierScene(); } } else if (addProfileLabel.getText().equals("Edit Profile")){ // EDIT PROFILE int status = 0; for (int i = 0; i < fields.length; i++){ TextField field = fields[i]; Label label = labels[i]; if (field.getText().isEmpty()){ label.setText(label.getText()+" (Required)"); label.setStyle("-fx-text-fill: #ff1474;"); status++; } } if (addProfileProfileImagePathLabel.getText().isEmpty()){ addProfileProfilePictureLabel.setText("Profile picture: (Required)"); addProfileProfilePictureLabel.setStyle("-fx-text-fill: #ff1474;"); status++; } if (status == 0){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (InputStream inputStream = new FileInputStream(jsonPath)) { InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); JsonObject profileKey = jsonObject.getAsJsonObject(keyProfileOnPopup.getText()); if (keyProfileOnPopup != null){ String imageFileName = addProfileProfileImagePathLabel.getText(); if(!(imageProfilePath+imageFileName).equals(profileKey.get("Image").getAsString())){ Path newSourceImagePath = Paths.get(addProfileProfileImageFullPathLabel.getText()); Path targetImagePath = Paths.get(imageProfilePath, imageFileName); try { Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException err){ err.printStackTrace(); } } profileKey.addProperty("Name", addProfileNameField.getText()); profileKey.addProperty("Email", addProfileEmailField.getText()); profileKey.addProperty("Phone", addProfileNoPhoneField.getText()); profileKey.addProperty("DateOfBirth", addProfileDateOfBirthField.getText()); profileKey.addProperty("Address", addProfileAddressField.getText()); profileKey.addProperty("Image", imageProfilePath+imageFileName); profileKey.addProperty("Password", profileKey.get("Password").getAsString()); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } } } catch (IOException err){ err.printStackTrace(); } } App.loadCashierScene(); } } @FXML private void onAddProfileApplyButtonMouseEnter(MouseEvent mouseEvent) { addProfileApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileApplyButtonMouseExit(MouseEvent mouseEvent) { addProfileApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileCancelButtonClick(ActionEvent actionEvent) { backgroundPopup.setVisible(false); addProfilePopup.setVisible(false); } @FXML private void onAddProfileCancelButtonMouseEnter(MouseEvent mouseEvent) { addProfileCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13"); } @FXML private void onAddProfileCancelButtonMouseExit(MouseEvent mouseEvent) { addProfileCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13"); } public void deleteProfileData(String keyProfile){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonPath = "./src/main/java/com/systeminventory/assets/json/cashierList.json"; try (InputStream inputStream = new FileInputStream(jsonPath)){ InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); jsonObject.remove(keyProfile); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } App.loadCashierScene(); } catch (IOException err){ err.printStackTrace(); } } @FXML private void onConfirmDeleteDeleteButtonProfileClick(ActionEvent event) { deleteProfileData(confirmDeleteKeyProfile.getText()); confirmDeleteVariableProfileName.setText(""); confirmDeleteKeyProfile.setText(""); confirmDeleteProfilePane.setVisible(false); backgroundPopup.setVisible(false); } @FXML private void onConfirmDeleteDeleteButtonProfileMouseEnter(MouseEvent event) { confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #e0005c;"+"-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteDeleteButtonProfileMouseExit(MouseEvent event) { confirmDeleteDeleteButtonProfile.setStyle("-fx-background-color: #ff1474;"+"-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileMouseEnter(MouseEvent event) { confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #19a6b7;" + "-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileMouseExit(MouseEvent mouseEvent) { confirmDeleteCancelButtonProfile.setStyle("-fx-background-color: #1ecbe1;" + "-fx-background-radius: 13;"); } @FXML private void onConfirmDeleteCancelButtonProfileClick(ActionEvent event) { backgroundPopup.setVisible(false); confirmDeleteProfilePane.setVisible(false); confirmDeleteKeyProfile.setText(""); confirmDeleteVariableProfileName.setText(""); }
private List<Cashier> readProfilesFromJson(String searchTerm) {
1
2023-11-18 02:53:02+00:00
8k
CivilisationPlot/CivilisationPlot_Papermc
src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java
[ { "identifier": "ConfigManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private final File file;\n File file_;\n private final FileConfiguration configFile;\n\n public ConfigManager(String filePath){\n this.file = new File(\"config/\" + filePath);\n\n FileManager.createResourceFile(file);\n\n this.file_ = new File(CivilisationPlot.getInstance().getDataFolder() + \"/\" + file.getPath());\n\n configFile = new YamlConfiguration();\n\n try {\n configFile.load(file_);\n } catch (IOException | InvalidConfigurationException e) {\n e.printStackTrace();\n }\n }\n\n public FileConfiguration getFileConfiguration(){\n return this.configFile;\n }\n\n public File getFile(){\n return this.file_;\n }\n}" }, { "identifier": "DatabaseManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/DatabaseManager.java", "snippet": "public class DatabaseManager {\n\n private static Connection co;\n private static final CivilisationPlot plugin = CivilisationPlot.getInstance();\n\n public Connection getConnection()\n {\n return co;\n }\n\n public void connection()\n {\n if(!isConnected())\n {\n try\n {\n String motorDriver = \"org.mariadb\";\n\n if (Objects.requireNonNull(plugin.getConfig().getString(\"Database.motor\")).equalsIgnoreCase(\"mysql\"))\n motorDriver = \"com.mysql.cj\";\n\n Class.forName(motorDriver + \".jdbc.Driver\"); //loading of the driver.\n co = DriverManager.getConnection(\"jdbc:\" + plugin.getConfig().getString(\"Database.motor\") + \"://\" + plugin.getConfig().getString(\"Database.host\") + \":\" + plugin.getConfig().getString(\"Database.port\") + \"/\" + plugin.getConfig().getString(\"Database.database_name\"), plugin.getConfig().getString(\"Database.user\"), plugin.getConfig().getString(\"Database.password\"));\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public void disconnection()\n {\n if (isConnected())\n {\n try\n {\n co.close();\n }\n catch(SQLException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n\n\n public static boolean isConnected()\n {\n try {\n return co != null && !co.isClosed() && plugin.getConfig().getBoolean(\"Database.enable\");\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n }\n return false;\n }\n\n public static boolean isOnline() {\n try {\n return !(co == null) || !co.isClosed();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public boolean doesTableExist(String tableName) {\n try {\n DatabaseMetaData metaData = co.getMetaData();\n ResultSet resultSet = metaData.getTables(null, null, tableName, null);\n\n return resultSet.next();\n } catch (SQLException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n\n public void setup(){\n try {\n\n //create the civils table\n if (!doesTableExist(\"civils\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE civils (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), name VARCHAR(50), money INT, nation VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the nations table\n if (!doesTableExist(\"nations\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE nations (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), uuid VARCHAR(50), leader_uuid VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the plots table\n if (!doesTableExist(\"plots\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE plots (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), wordlName VARCHAR(50), xCoordinates DOUBLE, yCoordinates DOUBLE, level TINYINT, propertyType VARCHAR(50), uuidProprietary VARCHAR(50));\");\n pstmt.execute();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "Civil", "path": "src/main/java/fr/laptoff/civilisationplot/civils/Civil.java", "snippet": "public class Civil {\n\n private String PlayerName;\n private float Money;\n private UUID Nation;\n private static final Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();\n private static final List<String> civilsList = new ArrayList<String>();\n\n public Civil(String playerName, float money, UUID nation){\n this.PlayerName = playerName;\n this.Money = money;\n this.Nation = nation;\n }\n\n public String getPlayerName(){\n return this.PlayerName;\n }\n\n public float getMoney(){\n return this.Money;\n }\n\n public List<String> getCivilsList(){\n return civilsList;\n }\n\n public Player getPlayer(){\n return Bukkit.getPlayer(this.PlayerName);\n }\n\n public UUID getUuid(){\n return getPlayer().getUniqueId();\n }\n\n public UUID getNationUuid(){\n return this.Nation;\n }\n\n public fr.laptoff.civilisationplot.nation.Nation getNation(){\n return fr.laptoff.civilisationplot.nation.Nation.getNation(this.Nation);\n }\n\n public void setNation(Nation nation){\n this.Nation = nation.getUuid();\n setNationDatabase(this.Nation);\n localRegister();\n }\n\n public void setMoney(float money){\n this.Money = money;\n setMoneyDatabase(money);\n localRegister();\n }\n\n public void setName(String playerName){\n this.PlayerName = playerName;\n setPlayerNameDatabase(playerName);\n localRegister();\n }\n\n public void setNationDatabase(UUID uuid){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE civils SET nation = '\" + uuid + \"' WHERE uuid = '\" + this.getUuid() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void setMoneyDatabase(float money){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE civils SET money = '\" + money + \"' WHERE uuid = '\" + this.getUuid() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void setPlayerNameDatabase(String name){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE civils SET name = '\" + name + \"' WHERE uuid = '\" + this.getUuid() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Boolean isExist(UUID uuid){\n civilsListFromDatabase();\n for(String uuidCivil : civilsList){\n if (UUID.fromString(uuidCivil) == uuid)\n return true;\n }\n return false;\n }\n\n public void localRegister(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/Civils/\" + this.getUuid().toString() + \".json\");\n Gson gson = new GsonBuilder().create();\n\n FileManager.createFile(file);\n FileManager.rewrite(file, gson.toJson(this));\n }\n\n public static Civil getCivilFromLocal(UUID uuid){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/Civils/\" + uuid.toString() + \".json\");\n\n if (!file.exists())\n return null;\n\n GsonBuilder builder = new GsonBuilder();\n Gson gson = builder.create();\n String content;\n try {\n content = Files.readString(Path.of(file.getPath()));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n return gson.fromJson(content, Civil.class);\n }\n\n public void insertIntoDatabase(){\n PreparedStatement pstmt = null;\n\n if (co == null)\n return;\n\n try {\n pstmt = co.prepareStatement(\"INSERT INTO civils (uuid, name, money, nation) VALUES (?, ?, ?, ?);\");\n pstmt.setString(1, getUuid().toString());\n pstmt.setString(2, this.PlayerName);\n pstmt.setFloat(3, this.Money);\n pstmt.setString(4, this.Nation.toString());\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static List<Civil> getCivilsListFromDatabase() throws SQLException {\n if (!CivilisationPlot.getInstance().getDatabase().isConnected())\n return null;\n\n List<Civil> list = new ArrayList<Civil>();\n\n PreparedStatement pstmt = CivilisationPlot.getInstance().getDatabase().getConnection().prepareStatement(\"SELECT * FROM civils;\");\n ResultSet result = pstmt.executeQuery();\n\n while (result.next()){\n Civil civil = new Civil(result.getString(\"name\"), result.getFloat(\"money\"), UUID.fromString(result.getString(\"nation\")));\n list.add(civil);\n }\n\n return list;\n }\n\n public static Civil getCivilFromDatabase(UUID uuid){\n\n if (!CivilisationPlot.getInstance().getDatabase().isConnected())\n return null;\n\n Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();\n Civil civil = null;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM civils WHERE uuid = '\" + uuid.toString() + \"';\");\n ResultSet result = pstmt.executeQuery();\n\n while (result.next()){\n civil = new Civil(result.getString(\"name\"), result.getFloat(\"money\"), UUID.fromString(result.getString(\"nation\")));\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n\n return civil;\n }\n\n public static Civil getCivil(UUID uuid){\n Civil civil = getCivilFromDatabase(uuid);\n if (civil == null)\n civil = getCivilFromLocal(uuid);\n\n return civil;\n }\n\n public static void localToDatabase(UUID uuid){\n Civil civil = getCivilFromLocal(uuid);\n civil.insertIntoDatabase();\n }\n\n public static void databaseToLocal(UUID uuid){\n Civil civil = getCivilFromDatabase(uuid);\n if (civil!=null)\n civil.localRegister();\n }\n\n public void save(){\n this.localRegister();\n this.insertIntoDatabase();\n civilsList.add(this.getUuid().toString());\n updateJsonFromCivilsList();\n }\n\n public void del() {\n\n //Delete from database\n if (CivilisationPlot.getInstance().getDatabase().isConnected()){\n String sql = \"DELETE FROM civils WHERE uuid = UUID(?);\";\n\n Connection connection = CivilisationPlot.getInstance().getDatabase().getConnection();\n\n try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {\n preparedStatement.setString(1, getUuid().toString());\n\n preparedStatement.execute();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n //Delete from Json\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/Civils/\" + getUuid().toString() + \".json\");\n\n if (file.exists())\n file.delete();\n\n //Delete from civilsList\n civilsList.remove(this);\n updateJsonFromCivilsList();\n }\n\n public static void civilsListFromJson(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/CivilsList.json\");\n FileManager.createFile(file);\n\n GsonBuilder builder = new GsonBuilder();\n Gson gson = builder.create();\n List<String> list = new ArrayList<String>();\n\n try {\n list = gson.fromJson(Files.readString(Path.of(file.getPath())), ArrayList.class);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n if (list == null)\n return;\n if (list.isEmpty())\n return;\n\n civilsList.clear();\n civilsList.addAll(list);\n }\n\n public static void civilsListFromDatabase(){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM civils;\");\n ResultSet result = pstmt.executeQuery();\n civilsList.clear();\n\n while(result.next()){\n Civil civil = new Civil(result.getString(\"name\"), result.getFloat(\"money\"), UUID.fromString(result.getString(\"nation\")));\n civilsList.add(civil.getUuid().toString());\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateJsonFromCivilsList(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/CivilsList.json\");\n FileManager.createFile(file);\n\n GsonBuilder builder = new GsonBuilder();\n Gson gson = builder.create();\n\n FileManager.rewrite(file, gson.toJson(civilsList));\n }\n\n public void addToCivilList(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Civils/CivilsList.json\");\n\n GsonBuilder builder = new GsonBuilder();\n Gson gson = builder.create();\n\n civilsList.add(this.getUuid().toString());\n FileManager.rewrite(file, gson.toJson(civilsList));\n }\n\n public static void load(){\n civilsListFromDatabase();\n updateJsonFromCivilsList();\n }\n}" }, { "identifier": "joinListener", "path": "src/main/java/fr/laptoff/civilisationplot/civils/joinListener.java", "snippet": "public class joinListener implements org.bukkit.event.Listener {\n\n private static final ConfigManager configMessages = new ConfigManager(\"english.yml\");\n private static final FileConfiguration config = configMessages.getFileConfiguration();\n\n @EventHandler\n public static void onJoin(PlayerJoinEvent e){\n Player player = e.getPlayer();\n\n if (!Civil.isExist(player.getUniqueId())){\n Civil civil = new Civil(player.getName(), Economy.getStartMoneyBalance(), null);\n civil.save();\n player.sendMessage(config.getString(\"Messages.Join.first_join\"));\n } else {\n Civil civil = Civil.getCivil(player.getUniqueId());\n player.sendMessage(config.getString(\"Messages.Join.other_join\"));\n }\n }\n}" }, { "identifier": "Nation", "path": "src/main/java/fr/laptoff/civilisationplot/nation/Nation.java", "snippet": "public class Nation {\n \n private String Name;\n private UUID Uuid;\n private Civil Leader;\n private File file;\n private static Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();\n private static List<String> nationList = new ArrayList<String>();\n\n \n public Nation(String name, UUID uuid, Civil leader){\n this.Name = name;\n this.Uuid = uuid;\n this.Leader = leader;\n leader.setNation(this);\n this.file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + this.Uuid);\n\n if (!isExistIntoLocal() || !isExistIntoDatabase())\n save();\n }\n\n public String getName(){\n return this.Name;\n }\n\n public UUID getUuid(){\n return this.Uuid;\n }\n\n public Civil getLeader(){\n return this.Leader;\n }\n\n public void setName(String name){\n this.Name = name;\n }\n\n public void setLeader(Civil leader){\n setLeaderDatabase(leader);\n leader.setNation(this);\n this.Leader = leader;\n }\n\n public void setNameDatabase(String name){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE nations SET name = '\" + name + \"' WHERE uuid = '\" + this.Uuid.toString() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void setLeaderDatabase(Civil leader){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE nations SET leader_uuid = '\" + leader.getUuid().toString() + \"' WHERE uuid = '\" + this.Uuid.toString() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n //Registers\n public void registerToList(){\n if (!nationList.contains(this.Uuid.toString()))\n nationList.add(this.Uuid.toString());\n }\n\n public void registerToLocal(){\n Gson gson = new GsonBuilder().create();\n\n FileManager.createFile(this.file);\n\n FileManager.rewrite(this.file, gson.toJson(this));\n }\n\n public void registerToDatabase(){\n if (co == null)\n return;\n\n if(this.isExistIntoDatabase())\n this.delFromDatabase();\n\n\n try{\n PreparedStatement pstmt = co.prepareStatement(\"INSERT INTO nations (name, uuid, leader_uuid) VALUES (?, ?, ?);\");\n pstmt.setString(1, this.Name);\n pstmt.setString(2, this.Uuid.toString());\n pstmt.setString(3, this.Leader.getUuid().toString());\n } catch(SQLException e){\n e.printStackTrace();\n }\n }\n\n //Getters\n public static Nation getFromNationList(UUID uuid){\n for (String nation : nationList){\n if (UUID.fromString(nation) == uuid)\n return getNation(UUID.fromString(nation));\n }\n return null;\n }\n\n public static Nation getFromLocal(UUID uuid){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + uuid.toString());\n\n if (!file.exists())\n return null;\n\n Gson gson = new GsonBuilder().create();\n\n try {\n return gson.fromJson(Files.readString(Path.of(file.getPath())), Nation.class);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Nation getFromDatabase(UUID uuid){\n if (!DatabaseManager.isOnline())\n return null;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations WHERE uuid = '\" + uuid + \"';\");\n ResultSet result = pstmt.executeQuery();\n\n while(result.next())\n return new Nation(result.getString(\"name\"), uuid, Civil.getCivil(UUID.fromString(result.getString(\"leader_uuid\"))));\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n\n return null;\n }\n\n public static Nation getNation(UUID uuid){\n if (getFromDatabase(uuid) == null)\n return getFromLocal(uuid);\n\n return getFromDatabase(uuid);\n }\n\n //Updates\n public static void updateLocalListFromProgramList(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/NationsList.json\");\n Gson gson = new GsonBuilder().create();\n\n\n FileManager.createFile(file);\n FileManager.rewrite(file, gson.toJson(nationList, ArrayList.class));\n }\n\n public static void updateProgramListFromLocalList(){\n Gson gson = new GsonBuilder().create();\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/NationsList.json\");\n\n FileManager.createFile(file);\n try {\n nationList = gson.fromJson(Files.readString(Path.of(file.getPath())), ArrayList.class);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateProgramListFromDatabase(){\n if (!DatabaseManager.isOnline())\n return;\n\n nationList.clear();\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations;\");\n ResultSet result = pstmt.executeQuery();\n\n while(result.next()){\n Nation nation = new Nation(result.getString(\"name\"), UUID.fromString(result.getString(\"uuid\")), Civil.getCivil(UUID.fromString(result.getString(\"leader_uuid\"))));\n nationList.add(nation.getUuid().toString());\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateLocalFromDatabase(){\n for (String uuid : nationList){\n\n Nation nation = getFromDatabase(UUID.fromString(uuid));\n\n if (nation == null)\n return;\n\n nation.registerToLocal();\n }\n }\n\n //Warning: This can break data's managements !\n public static void updateDatabaseFromLocal(){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"DELETE FROM nations;\");\n pstmt.execute();\n\n for (String uuid : nationList){\n Nation nation = getFromLocal(UUID.fromString(uuid));\n\n if (nation == null)\n return;\n\n nation.registerToDatabase();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n //Deletes\n public void delFromNationList(){\n nationList.remove(this.Uuid.toString());\n }\n\n public void delFromLocal(){\n this.file.delete();\n }\n\n public void delFromDatabase(){\n if (co == null)\n return;\n\n if (!isExistIntoDatabase())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"DELETE FROM nations WHERE uuid = UUID(?);\");\n pstmt.setString(1, this.Uuid.toString());\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void del(){\n this.delFromDatabase();\n this.delFromLocal();\n this.delFromNationList();\n }\n\n public boolean isExistIntoLocal(){\n return new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + this.Uuid).exists();\n }\n\n public boolean isExistIntoDatabase(){\n if (co == null)\n return false;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations WHERE uuid = '\" + this.Uuid + \"';\");\n ResultSet result = pstmt.executeQuery();\n\n return result.next();\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void save(){\n registerToDatabase();\n registerToLocal();\n registerToList();\n updateLocalListFromProgramList();\n }\n\n public static void load(){\n updateProgramListFromDatabase();\n updateLocalListFromProgramList();\n updateLocalFromDatabase();\n }\n}" } ]
import fr.laptoff.civilisationplot.Managers.ConfigManager; import fr.laptoff.civilisationplot.Managers.DatabaseManager; import fr.laptoff.civilisationplot.civils.Civil; import fr.laptoff.civilisationplot.civils.joinListener; import fr.laptoff.civilisationplot.nation.Nation; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; import java.util.logging.Logger;
5,949
package fr.laptoff.civilisationplot; public final class CivilisationPlot extends JavaPlugin { public static final Logger LOGGER = Logger.getLogger("CivilisationPlot"); private static CivilisationPlot instance; private DatabaseManager database; private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml) @Override public void onEnable() { instance = this; saveDefaultConfig(); ConfigManager configManagerMessages = new ConfigManager(getConfig().getString("Language.language")); configMessages = configManagerMessages.getFileConfiguration(); if (getConfig().getBoolean("Database.enable")){ database = new DatabaseManager(); database.connection(); database.setup(); LOGGER.info(configMessages.getString("Messages.Database.success_connection")); } Civil.load(); Nation.load(); LOGGER.info("#### ## ### ## ## ## ###### ### ##"); LOGGER.info("## ## ## ## ## ## ## ##"); LOGGER.info("## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####"); LOGGER.info("## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##"); LOGGER.info("## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##"); LOGGER.info("## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##"); LOGGER.info("#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###");
package fr.laptoff.civilisationplot; public final class CivilisationPlot extends JavaPlugin { public static final Logger LOGGER = Logger.getLogger("CivilisationPlot"); private static CivilisationPlot instance; private DatabaseManager database; private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml) @Override public void onEnable() { instance = this; saveDefaultConfig(); ConfigManager configManagerMessages = new ConfigManager(getConfig().getString("Language.language")); configMessages = configManagerMessages.getFileConfiguration(); if (getConfig().getBoolean("Database.enable")){ database = new DatabaseManager(); database.connection(); database.setup(); LOGGER.info(configMessages.getString("Messages.Database.success_connection")); } Civil.load(); Nation.load(); LOGGER.info("#### ## ### ## ## ## ###### ### ##"); LOGGER.info("## ## ## ## ## ## ## ##"); LOGGER.info("## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####"); LOGGER.info("## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##"); LOGGER.info("## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##"); LOGGER.info("## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##"); LOGGER.info("#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###");
getServer().getPluginManager().registerEvents(new joinListener(), this);
3
2023-11-11 18:26:55+00:00
8k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/MeteorRejectsAddon.java
[ { "identifier": "RadarHud", "path": "src/main/java/anticope/rejects/gui/hud/RadarHud.java", "snippet": "public class RadarHud extends HudElement {\n public static final HudElementInfo<RadarHud> INFO = new HudElementInfo<>(MeteorRejectsAddon.HUD_GROUP, \"radar\", \"Draws a Radar on your HUD telling you where entities are.\", RadarHud::new);\n\n private final SettingGroup sgGeneral = settings.getDefaultGroup();\n\n private final Setting<SettingColor> backgroundColor = sgGeneral.add(new ColorSetting.Builder()\n .name(\"background-color\")\n .description(\"Color of background.\")\n .defaultValue(new SettingColor(0, 0, 0, 64))\n .build()\n );\n\n\n private final Setting<Set<EntityType<?>>> entities = sgGeneral.add(new EntityTypeListSetting.Builder()\n .name(\"entities\")\n .description(\"Select specific entities.\")\n .defaultValue(EntityType.PLAYER)\n .build()\n );\n\n private final Setting<Boolean> letters = sgGeneral.add(new BoolSetting.Builder()\n .name(\"letters\")\n .description(\"Use entity's type first letter.\")\n .defaultValue(true)\n .build()\n );\n\n private final Setting<Boolean> showWaypoints = sgGeneral.add(new BoolSetting.Builder()\n .name(\"waypoints\")\n .description(\"Show waypoints.\")\n .defaultValue(false)\n .build()\n );\n\n private final Setting<Double> scale = sgGeneral.add(new DoubleSetting.Builder()\n .name(\"scale\")\n .description(\"The scale.\")\n .defaultValue(1)\n .min(1)\n .sliderRange(0.01, 5)\n .onChanged(aDouble -> calculateSize())\n .build()\n );\n\n private final Setting<Double> zoom = sgGeneral.add(new DoubleSetting.Builder()\n .name(\"zoom\")\n .description(\"Radar zoom.\")\n .defaultValue(1)\n .min(0.01)\n .sliderRange(0.01, 3)\n .build()\n );\n\n public RadarHud() {\n super(INFO);\n calculateSize();\n }\n\n public void calculateSize() {\n setSize(200 * scale.get(), 200 * scale.get());\n }\n\n @Override\n public void render(HudRenderer renderer) {\n ESP esp = Modules.get().get(ESP.class);\n if (esp == null) return;\n renderer.post(() -> {\n if (mc.player == null) return;\n double width = getWidth();\n double height = getHeight();\n Renderer2D.COLOR.begin();\n Renderer2D.COLOR.quad(x, y, width, height, backgroundColor.get());\n Renderer2D.COLOR.render(null);\n if (mc.world != null) {\n for (Entity entity : mc.world.getEntities()) {\n if (!entities.get().contains(entity.getType())) return;\n double xPos = ((entity.getX() - mc.player.getX()) * scale.get() * zoom.get() + width/2);\n double yPos = ((entity.getZ() - mc.player.getZ()) * scale.get() * zoom.get() + height/2);\n if (xPos < 0 || yPos < 0 || xPos > width - scale.get() || yPos > height - scale.get()) continue;\n String icon = \"*\";\n if (letters.get()) \n icon = entity.getType().getUntranslatedName().substring(0,1).toUpperCase();\n Color c = esp.getColor(entity);\n if (c == null) c = Color.WHITE;\n renderer.text(icon, xPos + x, yPos + y, c, false);\n }\n }\n if (showWaypoints.get()) {\n for (Waypoint waypoint : Waypoints.get()) {\n BlockPos blockPos = waypoint.getPos();\n Vec3d coords = new Vec3d(blockPos.getX() + 0.5, blockPos.getY(), blockPos.getZ() + 0.5);\n double xPos = ((coords.getX() - mc.player.getX()) * scale.get() * zoom.get() + width / 2);\n double yPos = ((coords.getZ() - mc.player.getZ()) * scale.get() * zoom.get() + height / 2);\n if (xPos < 0 || yPos < 0 || xPos > width - scale.get() || yPos > height - scale.get()) continue;\n String icon = \"*\";\n if (letters.get() && waypoint.name.get().length() > 0)\n icon = waypoint.name.get().substring(0, 1);\n renderer.text(icon, xPos + x, yPos + y, waypoint.color.get(), false);\n }\n }\n Renderer2D.COLOR.render(null);\n });\n \n }\n \n}" }, { "identifier": "MeteorRoundedGuiTheme", "path": "src/main/java/anticope/rejects/gui/themes/rounded/MeteorRoundedGuiTheme.java", "snippet": "public class MeteorRoundedGuiTheme extends GuiTheme {\n private final SettingGroup sgGeneral = settings.getDefaultGroup();\n private final SettingGroup sgColors = settings.createGroup(\"Colors\");\n private final SettingGroup sgTextColors = settings.createGroup(\"Text\");\n private final SettingGroup sgBackgroundColors = settings.createGroup(\"Background\");\n private final SettingGroup sgOutline = settings.createGroup(\"Outline\");\n private final SettingGroup sgSeparator = settings.createGroup(\"Separator\");\n private final SettingGroup sgScrollbar = settings.createGroup(\"Scrollbar\");\n private final SettingGroup sgSlider = settings.createGroup(\"Slider\");\n private final SettingGroup sgStarscript = settings.createGroup(\"Starscript\");\n\n // General\n\n public final Setting<Double> scale = sgGeneral.add(new DoubleSetting.Builder()\n .name(\"scale\")\n .description(\"Scale of the GUI.\")\n .defaultValue(1)\n .min(0.75)\n .sliderMin(0.75)\n .sliderMax(4)\n .onSliderRelease()\n .onChanged(aDouble -> {\n if (mc.currentScreen instanceof WidgetScreen) ((WidgetScreen) mc.currentScreen).invalidate();\n })\n .build()\n );\n\n public final Setting<AlignmentX> moduleAlignment = sgGeneral.add(new EnumSetting.Builder<AlignmentX>()\n .name(\"module-alignment\")\n .description(\"How module titles are aligned.\")\n .defaultValue(AlignmentX.Center)\n .build()\n );\n\n public final Setting<Boolean> categoryIcons = sgGeneral.add(new BoolSetting.Builder()\n .name(\"category-icons\")\n .description(\"Adds item icons to module categories.\")\n .defaultValue(false)\n .build()\n );\n\n public final Setting<Boolean> hideHUD = sgGeneral.add(new BoolSetting.Builder()\n .name(\"hide-HUD\")\n .description(\"Hide HUD when in GUI.\")\n .defaultValue(false)\n .onChanged(v -> {\n if (mc.currentScreen instanceof WidgetScreen) mc.options.hudHidden = v;\n })\n .build()\n );\n\n public final Setting<Integer> round = sgGeneral.add(new IntSetting.Builder()\n .name(\"round\")\n .description(\"How much windows should be rounded\")\n .defaultValue(0)\n .min(0)\n .max(20)\n .sliderMin(0)\n .sliderMax(15)\n .build()\n );\n\n // Colors\n\n public final Setting<SettingColor> accentColor = color(\"accent\", \"Main color of the GUI.\", new SettingColor(135, 0, 255));\n public final Setting<SettingColor> checkboxColor = color(\"checkbox\", \"Color of checkbox.\", new SettingColor(135, 0, 255));\n public final Setting<SettingColor> plusColor = color(\"plus\", \"Color of plus button.\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> minusColor = color(\"minus\", \"Color of minus button.\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> favoriteColor = color(\"favorite\", \"Color of checked favorite button.\", new SettingColor(255, 255, 0));\n\n // Text\n\n public final Setting<SettingColor> textColor = color(sgTextColors, \"text\", \"Color of text.\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> textSecondaryColor = color(sgTextColors, \"text-secondary-text\", \"Color of secondary text.\", new SettingColor(150, 150, 150));\n public final Setting<SettingColor> textHighlightColor = color(sgTextColors, \"text-highlight\", \"Color of text highlighting.\", new SettingColor(45, 125, 245, 100));\n public final Setting<SettingColor> titleTextColor = color(sgTextColors, \"title-text\", \"Color of title text.\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> loggedInColor = color(sgTextColors, \"logged-in-text\", \"Color of logged in account name.\", new SettingColor(45, 225, 45));\n public final Setting<SettingColor> placeholderColor = color(sgTextColors, \"placeholder\", \"Color of placeholder text.\", new SettingColor(255, 255, 255, 20));\n\n // Background\n\n public final ThreeStateColorSetting backgroundColor = new ThreeStateColorSetting(\n sgBackgroundColors,\n \"background\",\n new SettingColor(20, 20, 20, 200),\n new SettingColor(30, 30, 30, 200),\n new SettingColor(40, 40, 40, 200)\n );\n\n public final Setting<SettingColor> moduleBackground = color(sgBackgroundColors, \"module-background\", \"Color of module background when active.\", new SettingColor(50, 50, 50));\n\n // Outline\n\n public final ThreeStateColorSetting outlineColor = new ThreeStateColorSetting(\n sgOutline,\n \"outline\",\n new SettingColor(0, 0, 0),\n new SettingColor(10, 10, 10),\n new SettingColor(20, 20, 20)\n );\n\n // Separator\n\n public final Setting<SettingColor> separatorText = color(sgSeparator, \"separator-text\", \"Color of separator text\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> separatorCenter = color(sgSeparator, \"separator-center\", \"Center color of separators.\", new SettingColor(255, 255, 255));\n public final Setting<SettingColor> separatorEdges = color(sgSeparator, \"separator-edges\", \"Color of separator edges.\", new SettingColor(225, 225, 225, 150));\n\n // Scrollbar\n\n public final ThreeStateColorSetting scrollbarColor = new ThreeStateColorSetting(\n sgScrollbar,\n \"Scrollbar\",\n new SettingColor(30, 30, 30, 200),\n new SettingColor(40, 40, 40, 200),\n new SettingColor(50, 50, 50, 200)\n );\n\n // Slider\n\n public final ThreeStateColorSetting sliderHandle = new ThreeStateColorSetting(\n sgSlider,\n \"slider-handle\",\n new SettingColor(0, 255, 180),\n new SettingColor(0, 240, 165),\n new SettingColor(0, 225, 150)\n );\n\n public final Setting<SettingColor> sliderLeft = color(sgSlider, \"slider-left\", \"Color of slider left part.\", new SettingColor(0, 150, 80));\n public final Setting<SettingColor> sliderRight = color(sgSlider, \"slider-right\", \"Color of slider right part.\", new SettingColor(50, 50, 50));\n\n // Starscript\n\n private final Setting<SettingColor> starscriptText = color(sgStarscript, \"starscript-text\", \"Color of text in Starscript code.\", new SettingColor(169, 183, 198));\n private final Setting<SettingColor> starscriptBraces = color(sgStarscript, \"starscript-braces\", \"Color of braces in Starscript code.\", new SettingColor(150, 150, 150));\n private final Setting<SettingColor> starscriptParenthesis = color(sgStarscript, \"starscript-parenthesis\", \"Color of parenthesis in Starscript code.\", new SettingColor(169, 183, 198));\n private final Setting<SettingColor> starscriptDots = color(sgStarscript, \"starscript-dots\", \"Color of dots in starscript code.\", new SettingColor(169, 183, 198));\n private final Setting<SettingColor> starscriptCommas = color(sgStarscript, \"starscript-commas\", \"Color of commas in starscript code.\", new SettingColor(169, 183, 198));\n private final Setting<SettingColor> starscriptOperators = color(sgStarscript, \"starscript-operators\", \"Color of operators in Starscript code.\", new SettingColor(169, 183, 198));\n private final Setting<SettingColor> starscriptStrings = color(sgStarscript, \"starscript-strings\", \"Color of strings in Starscript code.\", new SettingColor(106, 135, 89));\n private final Setting<SettingColor> starscriptNumbers = color(sgStarscript, \"starscript-numbers\", \"Color of numbers in Starscript code.\", new SettingColor(104, 141, 187));\n private final Setting<SettingColor> starscriptKeywords = color(sgStarscript, \"starscript-keywords\", \"Color of keywords in Starscript code.\", new SettingColor(204, 120, 50));\n private final Setting<SettingColor> starscriptAccessedObjects = color(sgStarscript, \"starscript-accessed-objects\", \"Color of accessed objects (before a dot) in Starscript code.\", new SettingColor(152, 118, 170));\n\n public MeteorRoundedGuiTheme() {\n super(\"Meteor Rounded\");\n\n settingsFactory = new DefaultSettingsWidgetFactory(this);\n }\n\n private Setting<SettingColor> color(SettingGroup group, String name, String description, SettingColor color) {\n return group.add(new ColorSetting.Builder()\n .name(name + \"-color\")\n .description(description)\n .defaultValue(color)\n .build());\n }\n private Setting<SettingColor> color(String name, String description, SettingColor color) {\n return color(sgColors, name, description, color);\n }\n\n // Widgets\n\n @Override\n public WWindow window(WWidget icon, String title) {\n return w(new WMeteorWindow(icon, title));\n }\n\n @Override\n public WLabel label(String text, boolean title, double maxWidth) {\n if (maxWidth == 0) return w(new WMeteorLabel(text, title));\n return w(new WMeteorMultiLabel(text, title, maxWidth));\n }\n\n @Override\n public WHorizontalSeparator horizontalSeparator(String text) {\n return w(new WMeteorHorizontalSeparator(text));\n }\n\n @Override\n public WVerticalSeparator verticalSeparator() {\n return w(new WMeteorVerticalSeparator());\n }\n\n @Override\n protected WButton button(String text, GuiTexture texture) {\n return w(new WMeteorButton(text, texture));\n }\n\n @Override\n public WMinus minus() {\n return w(new WMeteorMinus());\n }\n\n @Override\n public WPlus plus() {\n return w(new WMeteorPlus());\n }\n\n @Override\n public WCheckbox checkbox(boolean checked) {\n return w(new WMeteorCheckbox(checked));\n }\n\n @Override\n public WSlider slider(double value, double min, double max) {\n return w(new WMeteorSlider(value, min, max));\n }\n\n @Override\n public WTextBox textBox(String text, String placeholder, CharFilter filter, Class<? extends WTextBox.Renderer> renderer) {\n return w(new WMeteorTextBox(text, placeholder, filter, renderer));\n }\n\n @Override\n public <T> WDropdown<T> dropdown(T[] values, T value) {\n return w(new WMeteorDropdown<>(values, value));\n }\n\n @Override\n public WTriangle triangle() {\n return w(new WMeteorTriangle());\n }\n\n @Override\n public WTooltip tooltip(String text) {\n return w(new WMeteorTooltip(text));\n }\n\n @Override\n public WView view() {\n return w(new WMeteorView());\n }\n\n @Override\n public WSection section(String title, boolean expanded, WWidget headerWidget) {\n return w(new WMeteorSection(title, expanded, headerWidget));\n }\n\n @Override\n public WAccount account(WidgetScreen screen, Account<?> account) {\n return w(new WMeteorAccount(screen, account));\n }\n\n @Override\n public WWidget module(Module module) {\n return w(new WMeteorModule(module));\n }\n\n @Override\n public WQuad quad(Color color) {\n return w(new WMeteorQuad(color));\n }\n\n @Override\n public WTopBar topBar() {\n return w(new WMeteorTopBar());\n }\n\n @Override\n public WFavorite favorite(boolean checked) {\n return w(new WMeteorFavorite(checked));\n }\n\n // Colors\n\n @Override\n public Color textColor() {\n return textColor.get();\n }\n\n @Override\n public Color textSecondaryColor() {\n return textSecondaryColor.get();\n }\n\n // Starscript\n\n @Override\n public Color starscriptTextColor() {\n return starscriptText.get();\n }\n\n @Override\n public Color starscriptBraceColor() {\n return starscriptBraces.get();\n }\n\n @Override\n public Color starscriptParenthesisColor() {\n return starscriptParenthesis.get();\n }\n\n @Override\n public Color starscriptDotColor() {\n return starscriptDots.get();\n }\n\n @Override\n public Color starscriptCommaColor() {\n return starscriptCommas.get();\n }\n\n @Override\n public Color starscriptOperatorColor() {\n return starscriptOperators.get();\n }\n\n @Override\n public Color starscriptStringColor() {\n return starscriptStrings.get();\n }\n\n @Override\n public Color starscriptNumberColor() {\n return starscriptNumbers.get();\n }\n\n @Override\n public Color starscriptKeywordColor() {\n return starscriptKeywords.get();\n }\n\n @Override\n public Color starscriptAccessedObjectColor() {\n return starscriptAccessedObjects.get();\n }\n\n // Other\n\n @Override\n public TextRenderer textRenderer() {\n return TextRenderer.get();\n }\n\n @Override\n public double scale(double value) {\n return value * scale.get();\n }\n\n @Override\n public boolean categoryIcons() {\n return categoryIcons.get();\n }\n\n @Override\n public boolean hideHUD() {\n return hideHUD.get();\n }\n\n public int roundAmount() {\n return round.get();\n }\n\n public class ThreeStateColorSetting {\n private final Setting<SettingColor> normal, hovered, pressed;\n\n public ThreeStateColorSetting(SettingGroup group, String name, SettingColor c1, SettingColor c2, SettingColor c3) {\n normal = color(group, name, \"Color of \" + name + \".\", c1);\n hovered = color(group, \"hovered-\" + name, \"Color of \" + name + \" when hovered.\", c2);\n pressed = color(group, \"pressed-\" + name, \"Color of \" + name + \" when pressed.\", c3);\n }\n\n public SettingColor get() {\n return normal.get();\n }\n\n public SettingColor get(boolean pressed, boolean hovered, boolean bypassDisableHoverColor) {\n if (pressed) return this.pressed.get();\n return (hovered && (bypassDisableHoverColor || !disableHoverColor)) ? this.hovered.get() : this.normal.get();\n }\n\n public SettingColor get(boolean pressed, boolean hovered) {\n return get(pressed, hovered, false);\n }\n }\n}" } ]
import anticope.rejects.commands.*; import anticope.rejects.gui.hud.RadarHud; import anticope.rejects.gui.themes.rounded.MeteorRoundedGuiTheme; import anticope.rejects.modules.*; import meteordevelopment.meteorclient.addons.GithubRepo; import meteordevelopment.meteorclient.addons.MeteorAddon; import meteordevelopment.meteorclient.commands.Commands; import meteordevelopment.meteorclient.gui.GuiThemes; import meteordevelopment.meteorclient.systems.Systems; import meteordevelopment.meteorclient.systems.hud.Hud; import meteordevelopment.meteorclient.systems.hud.HudGroup; import meteordevelopment.meteorclient.systems.modules.Category; import meteordevelopment.meteorclient.systems.modules.Modules; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.item.Items; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
5,766
package anticope.rejects; public class MeteorRejectsAddon extends MeteorAddon { public static final Logger LOG = LoggerFactory.getLogger("Rejects"); public static final Category CATEGORY = new Category("Rejects", Items.BARRIER.getDefaultStack()); public static final HudGroup HUD_GROUP = new HudGroup("Rejects"); @Override public void onInitialize() { LOG.info("Initializing Meteor Rejects Addon"); // Modules Modules modules = Modules.get(); modules.add(new BetterAimbot()); modules.add(new NewerNewChunks()); modules.add(new BaseFinderNew()); modules.add(new Shield()); modules.add(new TestModule()); modules.add(((new HitboxDesync()))); modules.add(new Announcer()); modules.add(new PacketLogger()); modules.add(new ManualCrystal()); modules.add(new TweakedAutoTool()); modules.add(new MacroAnchorAuto()); modules.add(new AutoMend()); modules.add(new BowBomb()); modules.add(new AutoCityPlus()); modules.add(new PistonAura()); modules.add(new CevBreaker()); modules.add(new AimAssist()); modules.add(new AntiBot()); modules.add(new AntiCrash()); modules.add(new AntiSpawnpoint()); modules.add(new AntiVanish()); modules.add(new ArrowDmg()); modules.add(new AutoBedTrap()); modules.add(new AutoCraft()); modules.add(new AutoExtinguish()); modules.add(new AutoFarm()); modules.add(new AutoGrind()); modules.add(new AutoLogin()); modules.add(new AutoPot()); modules.add(new AutoSoup()); modules.add(new AutoTNT()); modules.add(new AutoWither()); modules.add(new BoatGlitch()); modules.add(new BlockIn()); modules.add(new BoatPhase()); modules.add(new Boost()); modules.add(new BungeeCordSpoof()); modules.add(new ChatBot()); modules.add(new ChestAura()); modules.add(new ChorusExploit()); modules.add(new ColorSigns()); modules.add(new Confuse()); modules.add(new CoordLogger()); modules.add(new CustomPackets()); modules.add(new ExtraElytra()); modules.add(new FullFlight()); modules.add(new GamemodeNotifier()); modules.add(new GhostMode()); modules.add(new Glide()); modules.add(new InstaMine()); modules.add(new ItemGenerator()); modules.add(new InteractionMenu()); modules.add(new Jetpack()); modules.add(new KnockbackPlus()); modules.add(new Lavacast()); modules.add(new MossBot()); modules.add(new NewChunks()); modules.add(new NoJumpDelay()); modules.add(new ObsidianFarm()); modules.add(new OreSim()); modules.add(new PacketFly()); modules.add(new Painter()); modules.add(new Rendering()); modules.add(new RoboWalk()); modules.add(new ShieldBypass()); modules.add(new SilentDisconnect()); modules.add(new SkeletonESP()); modules.add(new SoundLocator()); modules.add(new TreeAura()); modules.add(new VehicleOneHit()); // Commands Commands.add(new CenterCommand()); Commands.add(new ClearChatCommand()); Commands.add(new GhostCommand()); Commands.add(new GiveCommand()); Commands.add(new HeadsCommand()); Commands.add(new KickCommand()); Commands.add(new LocateCommand()); Commands.add(new PanicCommand()); Commands.add(new ReconnectCommand()); Commands.add(new ServerCommand()); Commands.add(new SaveSkinCommand()); Commands.add(new SeedCommand()); Commands.add(new SetBlockCommand()); Commands.add(new SetVelocityCommand()); Commands.add(new TeleportCommand()); Commands.add(new TerrainExport()); Commands.add(new EntityDesyncCommand()); Commands.add(new BaseFinderNewCommands()); Commands.add(new NewChunkCounter()); // HUD Hud hud = Systems.get(Hud.class);
package anticope.rejects; public class MeteorRejectsAddon extends MeteorAddon { public static final Logger LOG = LoggerFactory.getLogger("Rejects"); public static final Category CATEGORY = new Category("Rejects", Items.BARRIER.getDefaultStack()); public static final HudGroup HUD_GROUP = new HudGroup("Rejects"); @Override public void onInitialize() { LOG.info("Initializing Meteor Rejects Addon"); // Modules Modules modules = Modules.get(); modules.add(new BetterAimbot()); modules.add(new NewerNewChunks()); modules.add(new BaseFinderNew()); modules.add(new Shield()); modules.add(new TestModule()); modules.add(((new HitboxDesync()))); modules.add(new Announcer()); modules.add(new PacketLogger()); modules.add(new ManualCrystal()); modules.add(new TweakedAutoTool()); modules.add(new MacroAnchorAuto()); modules.add(new AutoMend()); modules.add(new BowBomb()); modules.add(new AutoCityPlus()); modules.add(new PistonAura()); modules.add(new CevBreaker()); modules.add(new AimAssist()); modules.add(new AntiBot()); modules.add(new AntiCrash()); modules.add(new AntiSpawnpoint()); modules.add(new AntiVanish()); modules.add(new ArrowDmg()); modules.add(new AutoBedTrap()); modules.add(new AutoCraft()); modules.add(new AutoExtinguish()); modules.add(new AutoFarm()); modules.add(new AutoGrind()); modules.add(new AutoLogin()); modules.add(new AutoPot()); modules.add(new AutoSoup()); modules.add(new AutoTNT()); modules.add(new AutoWither()); modules.add(new BoatGlitch()); modules.add(new BlockIn()); modules.add(new BoatPhase()); modules.add(new Boost()); modules.add(new BungeeCordSpoof()); modules.add(new ChatBot()); modules.add(new ChestAura()); modules.add(new ChorusExploit()); modules.add(new ColorSigns()); modules.add(new Confuse()); modules.add(new CoordLogger()); modules.add(new CustomPackets()); modules.add(new ExtraElytra()); modules.add(new FullFlight()); modules.add(new GamemodeNotifier()); modules.add(new GhostMode()); modules.add(new Glide()); modules.add(new InstaMine()); modules.add(new ItemGenerator()); modules.add(new InteractionMenu()); modules.add(new Jetpack()); modules.add(new KnockbackPlus()); modules.add(new Lavacast()); modules.add(new MossBot()); modules.add(new NewChunks()); modules.add(new NoJumpDelay()); modules.add(new ObsidianFarm()); modules.add(new OreSim()); modules.add(new PacketFly()); modules.add(new Painter()); modules.add(new Rendering()); modules.add(new RoboWalk()); modules.add(new ShieldBypass()); modules.add(new SilentDisconnect()); modules.add(new SkeletonESP()); modules.add(new SoundLocator()); modules.add(new TreeAura()); modules.add(new VehicleOneHit()); // Commands Commands.add(new CenterCommand()); Commands.add(new ClearChatCommand()); Commands.add(new GhostCommand()); Commands.add(new GiveCommand()); Commands.add(new HeadsCommand()); Commands.add(new KickCommand()); Commands.add(new LocateCommand()); Commands.add(new PanicCommand()); Commands.add(new ReconnectCommand()); Commands.add(new ServerCommand()); Commands.add(new SaveSkinCommand()); Commands.add(new SeedCommand()); Commands.add(new SetBlockCommand()); Commands.add(new SetVelocityCommand()); Commands.add(new TeleportCommand()); Commands.add(new TerrainExport()); Commands.add(new EntityDesyncCommand()); Commands.add(new BaseFinderNewCommands()); Commands.add(new NewChunkCounter()); // HUD Hud hud = Systems.get(Hud.class);
hud.register(RadarHud.INFO);
0
2023-11-13 08:11:28+00:00
8k
stiemannkj1/java-utilities
src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java
[ { "identifier": "binarySearchArrayPrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(prefixes);\n}" }, { "identifier": "binarySearchArraySuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> binarySearchArraySuffixMapping(\n final Map<String, T> suffixes) {\n return new BinarySearchArraySuffixMapping<>(suffixes);\n}" }, { "identifier": "limitedCharArrayTriePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> limitedCharArrayTriePrefixMapping(\n final char min, final char max, final Map<String, T> prefixes) {\n return new LimitedCharArrayTriePrefixMapping<>(min, max, prefixes);\n}" }, { "identifier": "limitedCharArrayTrieSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> limitedCharArrayTrieSuffixMapping(\n final char min, final char max, final Map<String, T> suffixes) {\n return new LimitedCharArrayTrieSuffixMapping<>(min, max, suffixes);\n}" }, { "identifier": "ImmutablePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutablePrefixMapping<T> extends ImmutablePrefixMatcher {\n\n @Override\n default boolean matchesAnyPrefix(final String string) {\n return keyAndValueForPrefix(string) != null;\n }\n\n default T valueForPrefix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForPrefix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForPrefix(final String string);\n}" }, { "identifier": "ImmutableSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutableSuffixMapping<T> extends ImmutableSuffixMatcher {\n\n @Override\n default boolean matchesAnySuffix(final String string) {\n return keyAndValueForSuffix(string) != null;\n }\n\n default T valueForSuffix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForSuffix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForSuffix(final String string);\n}" }, { "identifier": "Pair", "path": "src/main/java/dev/stiemannkj1/util/Pair.java", "snippet": "public class Pair<T1, T2> implements Map.Entry<T1, T2> {\n public final T1 first;\n public final T2 second;\n\n private Pair(final T1 first, final T2 second) {\n this.first = first;\n this.second = second;\n }\n\n public T1 first() {\n return first;\n }\n\n public T2 second() {\n return second;\n }\n\n public T1 left() {\n return first;\n }\n\n public T2 right() {\n return second;\n }\n\n public T1 key() {\n return first;\n }\n\n public T2 value() {\n return second;\n }\n\n @Override\n public T1 getKey() {\n return first;\n }\n\n @Override\n public T2 getValue() {\n return second;\n }\n\n @Override\n public T2 setValue(final T2 value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(final Object o) {\n\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Pair<?, ?> pair = (Pair<?, ?>) o;\n\n return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(first, second);\n }\n\n @Override\n public String toString() {\n return \"{\" + first + ',' + second + '}';\n }\n\n public static <T1, T2> Pair<T1, T2> of(final T1 first, final T2 second) {\n return new Pair<>(first, second);\n }\n\n public static <K, V> Pair<K, V> fromEntry(final Map.Entry<K, V> entry) {\n return new Pair<>(entry.getKey(), entry.getValue());\n }\n\n public static final class NameValue<V> extends Pair<String, V> {\n private NameValue(final String name, final V value) {\n super(name, value);\n }\n\n public String name() {\n return first;\n }\n }\n\n public static <V> NameValue<V> nameValuePair(final String name, final V value) {\n return new NameValue<>(name, value);\n }\n}" } ]
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping; import dev.stiemannkj1.util.Pair; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource;
3,919
suffixes.put("aaa", 4); suffixMap = newSuffixMap(suffixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_suffixes_with_matching_prefixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newSuffixMap(suffixes)); } static Stream<Map<String, Integer>> invalidSuffixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidSuffixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> suffixes) { final Class<? extends Exception> expectedExceptionType = suffixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes)); } ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes); } private static void assertFirstMatchSearchTakesLessSteps( String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) { final AtomicLong firstSearchSteps = new AtomicLong(0); final AtomicLong longestSearchSteps = new AtomicLong(0); final Pair<String, Integer> firstMatch = fixMapping.getKeyAndValue(false, string, firstSearchSteps); if (expectedValue != null) { assertNotNull(firstMatch); } else { assertNull(firstMatch); } final Pair<String, Integer> longestMatch = fixMapping.getKeyAndValue(true, string, longestSearchSteps); if (expectedValue != null) { assertNotNull(longestMatch); } else { assertNull(longestMatch); } assertTrue(firstSearchSteps.get() <= longestSearchSteps.get()); } static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { return binarySearchArrayPrefixMapping(prefixes); } @CsvSource( value = { "abdicate,abd,abdicate,3,11,8,8", "abdicated,abd,abdicate,3,14,8,11", }) @ParameterizedTest @Override public void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { PrefixMappersTests.super.detects_prefixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests { @Override public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) {
/* Copyright 2023 Kyle J. Stiemann 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 dev.stiemannkj1.collection.fixmapping; final class FixMappingsTests { // TODO test unicode interface PrefixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "abe,true,1", "abd,true,2", "aba,false,null", "abd,true,2", "abdi,true,2", "abdic,true,2", "abdica,true,2", "abdicat,true,2", "abdicat,true,2", "abdicate,true,3", "abdicated,true,3", "x,false,null", "xy,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_prefixes( final String string, final boolean expectPrefixed, final Integer expectedValue) { // Test odd number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); // Test odd number of prefixes. prefixes.put("xyz", 4); prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); } @SuppressWarnings("unchecked") default void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of prefixes. prefixes.put("aaa", 4); prefixMap = newPrefixMap(prefixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_prefixes_with_matching_suffixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newPrefixMap(suffixes)); } static Stream<Map<String, Integer>> invalidPrefixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidPrefixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> prefixes) { final Class<? extends Exception> expectedExceptionType = prefixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes)); } ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes); } interface SuffixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "1abc,true,0", "abe,true,1", "abed,false,null", "abd,false,null", "aba,false,null", "at,false,null", "ate,true,2", "cate,true,2", "icate,true,2", "dicate,true,2", "bdicate,true,2", "abdicate,true,3", "i abdicate,true,3", "abdicated,false,null", "z,false,null", "yz,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_suffixes( final String string, final boolean expectSuffixed, final Integer expectedValue) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map; ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes); assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string)); assertEquals(expectedValue, suffixMap.valueForSuffix(string)); assertEquals( getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap); // Test odd number of suffixes. suffixes.put("xyz", 4); suffixMap = newSuffixMap(suffixes); assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string)); assertEquals(expectedValue, suffixMap.valueForSuffix(string)); assertEquals( getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap); } @SuppressWarnings("unchecked") default void detects_suffixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map; ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, suffixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of suffixes. suffixes.put("aaa", 4); suffixMap = newSuffixMap(suffixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_suffixes_with_matching_prefixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newSuffixMap(suffixes)); } static Stream<Map<String, Integer>> invalidSuffixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidSuffixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> suffixes) { final Class<? extends Exception> expectedExceptionType = suffixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes)); } ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes); } private static void assertFirstMatchSearchTakesLessSteps( String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) { final AtomicLong firstSearchSteps = new AtomicLong(0); final AtomicLong longestSearchSteps = new AtomicLong(0); final Pair<String, Integer> firstMatch = fixMapping.getKeyAndValue(false, string, firstSearchSteps); if (expectedValue != null) { assertNotNull(firstMatch); } else { assertNull(firstMatch); } final Pair<String, Integer> longestMatch = fixMapping.getKeyAndValue(true, string, longestSearchSteps); if (expectedValue != null) { assertNotNull(longestMatch); } else { assertNull(longestMatch); } assertTrue(firstSearchSteps.get() <= longestSearchSteps.get()); } static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { return binarySearchArrayPrefixMapping(prefixes); } @CsvSource( value = { "abdicate,abd,abdicate,3,11,8,8", "abdicated,abd,abdicate,3,14,8,11", }) @ParameterizedTest @Override public void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { PrefixMappersTests.super.detects_prefixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests { @Override public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) {
return binarySearchArraySuffixMapping(suffixes);
1
2023-11-12 05:05:22+00:00
8k
slow3586/HypersomniaMapGen
src/main/java/com/slow3586/Main.java
[ { "identifier": "RoomStyle", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}" }, { "identifier": "ExternalResource", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Builder\n@Value\npublic static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n}" }, { "identifier": "WHITE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Color WHITE = new Color(255, 255, 255, 255);" }, { "identifier": "Layer", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class Layer {\n String id;\n List<String> nodes;\n}" }, { "identifier": "Node", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\n@Builder\npublic static class Node {\n @Builder.Default\n String id = String.valueOf(Map.nodeIndex.getAndIncrement());\n String type;\n float[] pos;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n Float rotation = 0.0f;\n String faction;\n String letter;\n Float positional_vibration;\n Float intensity_vibration;\n Falloff falloff;\n int[] color;\n int num_particles;\n\n static final String FACTION_RESISTANCE = \"RESISTANCE\";\n static final String TYPE_BOMBSITE = \"bombsite\";\n static final String LETTER_A = \"A\";\n static final String TYPE_BUY_ZONE = \"buy_zone\";\n static final String FACTION_METROPOLIS = \"METROPOLIS\";\n static final String TYPE_TEAM_SPAWN = \"team_spawn\";\n static final String LETTER_B = \"B\";\n\n @Value\n public static class Falloff {\n float radius;\n int strength;\n }\n\n @Builder\n @Value\n public static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n }\n\n @Value\n @Builder\n public static class AsPhysical {\n // lombok \"'is' getter\" fix\n @JsonProperty(\"is_static\")\n @Getter(AccessLevel.NONE)\n boolean is_static;\n @JsonProperty(\"is_see_through\")\n @Getter(AccessLevel.NONE)\n boolean is_see_through;\n @JsonProperty(\"is_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_throw_through;\n @JsonProperty(\"is_melee_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_melee_throw_through;\n @JsonProperty(\"is_shoot_through\")\n @Getter(AccessLevel.NONE)\n boolean is_shoot_through;\n Float density; // 0.7\n Float friction; // 0.0\n Float bounciness; // 0.2\n Float penetrability; // 1\n Float collision_sound_sensitivity; // 1\n Float linear_damping; // 6.5\n Float angular_damping; // 6.5\n CustomShape custom_shape;\n\n static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();\n\n @Value\n public static class CustomShape {\n float[][] source_polygon;\n\n public CustomShape mul(float mul) {\n float[][] result = new float[4][2];\n for (int y = 0; y < 4; y++) {\n for (int x = 0; x < 2; x++) {\n result[y][x] = CRATE_SHAPE.source_polygon[y][x] * mul;\n }\n }\n return new CustomShape(result);\n }\n\n static final CustomShape CRATE_SHAPE = new CustomShape(\n new float[][]{\n new float[]{-32.0f, -32.0f},\n new float[]{32.0f, -32.0f},\n new float[]{32.0f, 32.0f},\n new float[]{-32.0f, 32.0f},\n });\n }\n }\n\n @Value\n public static class AsNonPhysical {\n boolean full_illumination;\n\n static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);\n }\n}" }, { "identifier": "AS_NON_PHYSICAL_DEFAULT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);" }, { "identifier": "AS_PHYSICAL_DEFAULT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();" }, { "identifier": "BASE_PNG_TEXTURE_FILENAME", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";" }, { "identifier": "CRATE_BLOCKING", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String CRATE_BLOCKING = \"crate_blocking\";" }, { "identifier": "CRATE_NON_BLOCKING", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";" }, { "identifier": "DOMAIN_FOREGROUND", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String DOMAIN_FOREGROUND = \"FOREGROUND\";" }, { "identifier": "DOMAIN_PHYSICAL", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String DOMAIN_PHYSICAL = \"PHYSICAL\";" }, { "identifier": "LINE_FLOOR", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String LINE_FLOOR = \"line_floor\";" }, { "identifier": "LINE_WALL", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String LINE_WALL = \"line_wall\";" }, { "identifier": "MAP_GFX_PATH", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String MAP_GFX_PATH = \"gfx/\";" }, { "identifier": "PNG_EXT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String PNG_EXT = \".png\";" }, { "identifier": "RESOURCE_FLOOR_ID", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_FLOOR_ID = \"style_floor\";" }, { "identifier": "RESOURCE_ID_PREFIX", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_ID_PREFIX = \"@\";" }, { "identifier": "RESOURCE_WALL_ID", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_WALL_ID = \"style_wall\";" }, { "identifier": "ROOM_NOISE_CIRCLE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";" }, { "identifier": "SHADOW_FLOOR_CORNER", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";" }, { "identifier": "SHADOW_FLOOR_LINE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";" }, { "identifier": "SHADOW_WALL_CORNER", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";" }, { "identifier": "SHADOW_WALL_LINE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_WALL_LINE = \"shadow_wall_line\";" }, { "identifier": "Playtesting", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class Playtesting {\n static final String QUICK_TEST = \"quick_test\";\n String mode;\n}" }, { "identifier": "CRATE_SIZE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Size CRATE_SIZE = new Size(104, 104);" }, { "identifier": "TILE_SIZE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Size TILE_SIZE = new Size(128, 128);" } ]
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.slow3586.Main.Room.RoomStyle; import com.slow3586.Main.Settings.Node.ExternalResource; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.ToString; import lombok.Value; import org.jooq.lambda.Sneaky; import org.jooq.lambda.function.Consumer1; import org.jooq.lambda.function.Consumer2; import org.jooq.lambda.function.Consumer4; import org.jooq.lambda.function.Function1; import org.jooq.lambda.function.Function3; import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static com.slow3586.Main.Color.WHITE; import static com.slow3586.Main.MapTile.TileType.DOOR; import static com.slow3586.Main.MapTile.TileType.WALL; import static com.slow3586.Main.Settings.Layer; import static com.slow3586.Main.Settings.Node; import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL; import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH; import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE; import static com.slow3586.Main.Settings.Playtesting; import static com.slow3586.Main.Size.CRATE_SIZE; import static com.slow3586.Main.Size.TILE_SIZE;
5,935
mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR; } } } } //endregion //region OUTPUT: PRINT MAP TO TEXT FILE final StringJoiner wallJoiner = new StringJoiner("\n"); wallJoiner.add("Walls:"); final StringJoiner heightJoiner = new StringJoiner("\n"); heightJoiner.add("Heights:"); final StringJoiner styleIndexJoiner = new StringJoiner("\n"); styleIndexJoiner.add("Styles:"); final StringJoiner carcassJoiner = new StringJoiner("\n"); carcassJoiner.add("Carcass:"); pointsRectArrayByRow(mapTilesCrop) .forEach(row -> { final StringBuilder wallJoinerRow = new StringBuilder(); final StringBuilder heightJoinerRow = new StringBuilder(); final StringBuilder styleIndexJoinerRow = new StringBuilder(); final StringBuilder carcassJoinerRow = new StringBuilder(); row.forEach(point -> { final MapTile mapTile = mapTilesCrop[point.y][point.x]; wallJoinerRow.append( mapTile.tileType == WALL ? "#" : mapTile.tileType == MapTile.TileType.DOOR ? "." : "_"); heightJoinerRow.append(mapTile.height); styleIndexJoinerRow.append(mapTile.styleIndex); carcassJoinerRow.append( mapTile.disabled && !mapTile.carcass ? "X" : mapTile.carcass || point.x == 0 || point.y == 0 ? "#" : "_"); }); wallJoiner.add(wallJoinerRow.toString()); heightJoiner.add(heightJoinerRow.toString()); styleIndexJoiner.add(styleIndexJoinerRow.toString()); carcassJoiner.add(carcassJoinerRow.toString()); }); final StringJoiner textJoiner = new StringJoiner("\n\n"); textJoiner.add(carcassJoiner.toString()); textJoiner.add(wallJoiner.toString()); textJoiner.add(heightJoiner.toString()); textJoiner.add(styleIndexJoiner.toString()); Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes()); //endregion //region OUTPUT: CREATE MAP JSON FILE //region BASE MAP JSON OBJECT final Map mapJson = new Map( new Meta( config.gameVersion, config.mapName, "2023-11-14 17:28:36.619839 UTC"), new About("Generated map"), new Settings( "bomb_defusal", config.ambientLightColor.intArray()), new Playtesting(Playtesting.QUICK_TEST), new ArrayList<>(), List.of(new Layer( "default", new ArrayList<>())), new ArrayList<>()); //endregion //region RESOURCES: FUNCTIONS final File texturesDir = new File("textures"); final Path mapGfxPath = mapDirectory.resolve("gfx"); if (!Files.exists(mapGfxPath)) { Files.createDirectories(mapGfxPath); } final BiConsumer<String, String> createTexture = Sneaky.biConsumer( (sourceFilename, targetFilename) -> { final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT); final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT); if (Files.exists(targetPath)) Files.delete(targetPath); Files.copy(sourcePath, targetPath); }); final Consumer<String> createTextureSameName = Sneaky.consumer( (filename) -> createTexture.accept(filename, filename)); final Function3<Integer, Integer, Boolean, String> getCrateName = ( final Integer roomStyleIndex, final Integer crateStyleIndex, final Boolean isBlocking ) -> "style" + roomStyleIndex + "_crate" + crateStyleIndex + "_" + (isBlocking ? "" : "non") + "blocking"; //endregion //region RESOURCES: ROOMS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT) .id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE) .stretch_when_resized(true) .domain(DOMAIN_FOREGROUND) .color(new Color(255, 255, 255, 150).intArray()) .build()); createTextureSameName.accept(ROOM_NOISE_CIRCLE); //endregion //region RESOURCES: STYLES IntStream.range(0, styles.length) .boxed() .forEach((final Integer roomStyleIndex) -> { final RoomStyle style = styles[roomStyleIndex];
package com.slow3586; public class Main { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static Random baseRandom; static Configuration config; static { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public static void main(String[] args) throws IOException { //region CONFIGURATION final String configStr = Files.readString(Path.of("config.json")); config = OBJECT_MAPPER.readValue(configStr, Configuration.class); baseRandom = new Random(config.randomSeed); final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName); //endregion //region GENERATION: ROOMS //region RANDOMIZE DIAGONAL ROOM SIZES final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize()) .limit(Math.max(config.roomsCount.x, config.roomsCount.y)) .toArray(Size[]::new); //endregion //region RANDOMIZE ROOM STYLES final RoomStyle[] styles = IntStream.range(0, config.styleCount) .boxed() .map(styleIndex -> new RoomStyle( config.styleHeightOverride.length > styleIndex ? config.styleHeightOverride[styleIndex] : styleIndex, config.floorMinMaxTintBase .randomize() .add(config.floorTintPerHeight.mul(styleIndex)), config.wallMinMaxTintBase .randomize() .add(config.wallTintPerHeight.mul(styleIndex)), nextInt(1, config.patternResourceCount), nextInt(1, config.patternResourceCount), config.patternMinMaxTintFloor.randomize(), config.patternMinMaxTintWall.randomize()) ).toArray(RoomStyle[]::new); //endregion final Room[][] rooms = new Room[config.roomsCount.y][config.roomsCount.x]; pointsRect(0, 0, config.roomsCount.x, config.roomsCount.y) .forEach(roomIndex -> { final boolean disableRoom = Arrays.asList(config.roomsDisabled).contains(roomIndex); final boolean disableDoorRight = Arrays.asList(config.roomsDoorRightDisabled).contains(roomIndex) || (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.RIGHT))); final boolean disableDoorDown = Arrays.asList(config.roomsDoorDownDisabled).contains(roomIndex) || (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.DOWN))); //region CALCULATE ABSOLUTE ROOM POSITION final Point roomPosAbs = new Point( Arrays.stream(diagonalRoomSizes) .limit(roomIndex.x) .map(Size::getW) .reduce(0, Integer::sum), Arrays.stream(diagonalRoomSizes) .limit(roomIndex.y) .map(Size::getH) .reduce(0, Integer::sum)); //endregion //region RANDOMIZE WALL final Size wallSize = config.wallMinMaxSize.randomize(); final Point wallOffset = new Point( -nextInt(0, Math.min(wallSize.w, config.wallMaxOffset.x)), -nextInt(0, Math.min(wallSize.h, config.wallMaxOffset.y))); //endregion //region RANDOMIZE DOOR final Size roomFloorSpace = new Size( diagonalRoomSizes[roomIndex.x].w + wallOffset.y, diagonalRoomSizes[roomIndex.y].h + wallOffset.x); final boolean needVerticalDoor = !disableDoorRight && roomIndex.x > 0 && roomIndex.x < rooms[0].length - 1; final boolean needHorizontalDoor = !disableDoorDown && roomIndex.y > 0 && roomIndex.y < rooms.length - 1; final Size doorSize = new Size( needHorizontalDoor ? Math.min(config.doorMinMaxWidth.randomizeWidth(), roomFloorSpace.w - 1) : 0, needVerticalDoor ? Math.min(config.doorMinMaxWidth.randomizeHeight(), roomFloorSpace.h - 1) : 0); final Point doorOffset = new Point( needHorizontalDoor ? nextInt(1, roomFloorSpace.w - doorSize.w + 1) : 0, needVerticalDoor ? nextInt(1, roomFloorSpace.h - doorSize.h + 1) : 0); //endregion //region RANDOMIZE STYLE final int styleIndex = nextInt(0, config.styleCount); final Size styleSize = new Size( roomIndex.x == config.roomsCount.x - 1 ? 1 : config.styleSizeMinMaxSize.randomizeWidth(), roomIndex.y == config.roomsCount.y - 1 ? 1 : config.styleSizeMinMaxSize.randomizeHeight()); //endregion //region PUT ROOM INTO ROOMS ARRAY rooms[roomIndex.y][roomIndex.x] = new Room( roomPosAbs, new Size( diagonalRoomSizes[roomIndex.x].w, diagonalRoomSizes[roomIndex.y].h), new Room.Rect( wallOffset.x, wallSize.w), new Room.Rect( wallOffset.y, wallSize.h), new Room.Rect( doorOffset.x, doorSize.w), new Room.Rect( doorOffset.y, doorSize.h), styleIndex, styleSize, disableRoom); //endregion }); //endregion //region GENERATION: BASE MAP TILE ARRAY final MapTile[][] mapTilesUncropped = pointsRectRows( Arrays.stream(diagonalRoomSizes) .mapToInt(r -> r.w + Math.max(config.styleSizeMinMaxSize.max.w, config.wallMaxOffset.x)) .sum() + 1, Arrays.stream(diagonalRoomSizes) .mapToInt(r -> r.h + Math.max(config.styleSizeMinMaxSize.max.h, config.wallMaxOffset.y)) .sum() + 1) .stream() .map(row -> row.stream() .map(point -> new MapTile( MapTile.TileType.FLOOR, null, false, false, null)) .toArray(MapTile[]::new) ).toArray(MapTile[][]::new); //endregion //region GENERATION: RENDER BASE ROOMS ONTO BASE MAP TILE ARRAY pointsRectArray(rooms) .forEach(roomIndex -> { final Room room = rooms[roomIndex.y][roomIndex.x]; //region FILL MAP TILES //region WALL HORIZONTAL pointsRect( room.roomPosAbs.x, room.roomPosAbs.y + room.roomSize.h + room.wallHoriz.offset, room.roomSize.w, room.wallHoriz.width ).forEach(pointAbs -> { final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR) || (pointAbs.x >= room.roomPosAbs.x + room.doorHoriz.offset && pointAbs.x < room.roomPosAbs.x + room.doorHoriz.offset + room.doorHoriz.width); mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); //endregion //region WALL VERTICAL pointsRect( room.roomPosAbs.x + room.roomSize.w + room.wallVert.offset, room.roomPosAbs.y, room.wallVert.width, room.roomSize.h ).forEach(pointAbs -> { final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR) || (pointAbs.y >= room.roomPosAbs.y + room.doorVert.offset && pointAbs.y < room.roomPosAbs.y + room.doorVert.offset + room.doorVert.width); mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); //endregion //region DISABLE FLOOR if (room.isDisabled()) { pointsRect( room.roomPosAbs.x, room.roomPosAbs.y, room.roomSize.w + room.wallVert.offset, room.roomSize.h + room.wallHoriz.offset ).forEach(pointAbs -> { final boolean isDoorTile = mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == DOOR; mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); } //endregion //region CARCASS HORIZONTAL pointsRect( room.roomPosAbs.x, room.roomPosAbs.y + room.roomSize.h, room.roomSize.w, 1 ).forEach(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true); //endregion //region CARCASS VERTICAL pointsRect( room.roomPosAbs.x + room.roomSize.w, room.roomPosAbs.y, 1, room.roomSize.h ).forEach(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true); //endregion //region TILE ROOM TYPE pointsRect( room.roomPosAbs.x, room.roomPosAbs.y, room.roomSize.w + room.styleSize.w, room.roomSize.h + room.styleSize.h ).stream() .map(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x]) .forEach(tile -> { if (tile.styleIndex == null) { tile.styleIndex = room.styleIndex; } tile.height = styles[room.styleIndex].height + (tile.tileType == WALL ? config.wallHeight : 0); }); //endregion //endregion }); //endregion //region GENERATION: CROP MAP final MapTile[][] mapTilesCrop; if (config.cropMap) { final Size croppedMapSize = new Size( Arrays.stream(diagonalRoomSizes) .limit(rooms[0].length) .map(s -> s.w) .reduce(0, Integer::sum) - diagonalRoomSizes[0].w + 1, Arrays.stream(diagonalRoomSizes) .limit(rooms.length) .map(s -> s.h) .reduce(0, Integer::sum) - diagonalRoomSizes[0].h + 1); final MapTile[][] temp = new MapTile[croppedMapSize.h][croppedMapSize.w]; for (int y = 0; y < croppedMapSize.h; y++) { temp[y] = Arrays.copyOfRange( mapTilesUncropped[y + diagonalRoomSizes[0].h], diagonalRoomSizes[0].w, diagonalRoomSizes[0].w + croppedMapSize.w); } mapTilesCrop = temp; } else { mapTilesCrop = mapTilesUncropped; } //endregion //region GENERATION: FIX MOST DOWN RIGHT TILE mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 1] = mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 2]; //endregion //region GENERATION: FIX DIAGONAL WALLS TOUCH WITH EMPTY SIDES // #_ _# // _# OR #_ final Function1<MapTile, Boolean> isWall = (s) -> s.tileType == MapTile.TileType.WALL; for (int iter = 0; iter < 2; iter++) { for (int y = 1; y < mapTilesCrop.length - 1; y++) { for (int x = 1; x < mapTilesCrop[y].length - 1; x++) { final boolean wall = isWall.apply(mapTilesCrop[y][x]); final boolean wallR = isWall.apply(mapTilesCrop[y][x + 1]); final boolean wallD = isWall.apply(mapTilesCrop[y + 1][x]); final boolean wallRD = isWall.apply(mapTilesCrop[y + 1][x + 1]); if ((wall && wallRD && !wallR && !wallD) || (!wall && !wallRD && wallR && wallD) ) { if (wall) mapTilesCrop[y][x].height -= config.wallHeight; mapTilesCrop[y][x].tileType = MapTile.TileType.FLOOR; if (wallR) mapTilesCrop[y][x + 1].height -= config.wallHeight; mapTilesCrop[y][x + 1].tileType = MapTile.TileType.FLOOR; if (wallD) mapTilesCrop[y + 1][x].height -= config.wallHeight; mapTilesCrop[y + 1][x].tileType = MapTile.TileType.FLOOR; if (wallRD) mapTilesCrop[y + 1][x + 1].height -= config.wallHeight; mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR; } } } } //endregion //region OUTPUT: PRINT MAP TO TEXT FILE final StringJoiner wallJoiner = new StringJoiner("\n"); wallJoiner.add("Walls:"); final StringJoiner heightJoiner = new StringJoiner("\n"); heightJoiner.add("Heights:"); final StringJoiner styleIndexJoiner = new StringJoiner("\n"); styleIndexJoiner.add("Styles:"); final StringJoiner carcassJoiner = new StringJoiner("\n"); carcassJoiner.add("Carcass:"); pointsRectArrayByRow(mapTilesCrop) .forEach(row -> { final StringBuilder wallJoinerRow = new StringBuilder(); final StringBuilder heightJoinerRow = new StringBuilder(); final StringBuilder styleIndexJoinerRow = new StringBuilder(); final StringBuilder carcassJoinerRow = new StringBuilder(); row.forEach(point -> { final MapTile mapTile = mapTilesCrop[point.y][point.x]; wallJoinerRow.append( mapTile.tileType == WALL ? "#" : mapTile.tileType == MapTile.TileType.DOOR ? "." : "_"); heightJoinerRow.append(mapTile.height); styleIndexJoinerRow.append(mapTile.styleIndex); carcassJoinerRow.append( mapTile.disabled && !mapTile.carcass ? "X" : mapTile.carcass || point.x == 0 || point.y == 0 ? "#" : "_"); }); wallJoiner.add(wallJoinerRow.toString()); heightJoiner.add(heightJoinerRow.toString()); styleIndexJoiner.add(styleIndexJoinerRow.toString()); carcassJoiner.add(carcassJoinerRow.toString()); }); final StringJoiner textJoiner = new StringJoiner("\n\n"); textJoiner.add(carcassJoiner.toString()); textJoiner.add(wallJoiner.toString()); textJoiner.add(heightJoiner.toString()); textJoiner.add(styleIndexJoiner.toString()); Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes()); //endregion //region OUTPUT: CREATE MAP JSON FILE //region BASE MAP JSON OBJECT final Map mapJson = new Map( new Meta( config.gameVersion, config.mapName, "2023-11-14 17:28:36.619839 UTC"), new About("Generated map"), new Settings( "bomb_defusal", config.ambientLightColor.intArray()), new Playtesting(Playtesting.QUICK_TEST), new ArrayList<>(), List.of(new Layer( "default", new ArrayList<>())), new ArrayList<>()); //endregion //region RESOURCES: FUNCTIONS final File texturesDir = new File("textures"); final Path mapGfxPath = mapDirectory.resolve("gfx"); if (!Files.exists(mapGfxPath)) { Files.createDirectories(mapGfxPath); } final BiConsumer<String, String> createTexture = Sneaky.biConsumer( (sourceFilename, targetFilename) -> { final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT); final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT); if (Files.exists(targetPath)) Files.delete(targetPath); Files.copy(sourcePath, targetPath); }); final Consumer<String> createTextureSameName = Sneaky.consumer( (filename) -> createTexture.accept(filename, filename)); final Function3<Integer, Integer, Boolean, String> getCrateName = ( final Integer roomStyleIndex, final Integer crateStyleIndex, final Boolean isBlocking ) -> "style" + roomStyleIndex + "_crate" + crateStyleIndex + "_" + (isBlocking ? "" : "non") + "blocking"; //endregion //region RESOURCES: ROOMS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT) .id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE) .stretch_when_resized(true) .domain(DOMAIN_FOREGROUND) .color(new Color(255, 255, 255, 150).intArray()) .build()); createTextureSameName.accept(ROOM_NOISE_CIRCLE); //endregion //region RESOURCES: STYLES IntStream.range(0, styles.length) .boxed() .forEach((final Integer roomStyleIndex) -> { final RoomStyle style = styles[roomStyleIndex];
final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex;
16
2023-11-18 14:36:04+00:00
8k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/PhoneResetActivity.java
[ { "identifier": "AppActivity", "path": "app/src/main/java/com/buaa/food/app/AppActivity.java", "snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n /** 加载对话框 */\n private BaseDialog mDialog;\n /** 对话框数量 */\n private int mDialogCount;\n\n /**\n * 当前加载对话框是否在显示中\n */\n public boolean isShowDialog() {\n return mDialog != null && mDialog.isShowing();\n }\n\n /**\n * 显示加载对话框\n */\n public void showDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n mDialogCount++;\n postDelayed(() -> {\n if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialog == null) {\n mDialog = new WaitDialog.Builder(this)\n .setCancelable(false)\n .create();\n }\n if (!mDialog.isShowing()) {\n mDialog.show();\n }\n }, 300);\n }\n\n /**\n * 隐藏加载对话框\n */\n public void hideDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialogCount > 0) {\n mDialogCount--;\n }\n\n if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {\n return;\n }\n\n mDialog.dismiss();\n }\n\n @Override\n protected void initLayout() {\n super.initLayout();\n\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n // 初始化沉浸式状态栏\n if (isStatusBarEnabled()) {\n getStatusBarConfig().init();\n\n // 设置标题栏沉浸\n if (getTitleBar() != null) {\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n /**\n * 是否使用沉浸式状态栏\n */\n protected boolean isStatusBarEnabled() {\n return true;\n }\n\n /**\n * 状态栏字体深色模式\n */\n protected boolean isStatusBarDarkFont() {\n return true;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n public ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式状态栏\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(@StringRes int id) {\n setTitle(getString(id));\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (getTitleBar() != null) {\n getTitleBar().setTitle(title);\n }\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null) {\n mTitleBar = obtainTitleBar(getContentView());\n }\n return mTitleBar;\n }\n\n @Override\n public void onLeftClick(View view) {\n onBackPressed();\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n super.startActivityForResult(intent, requestCode, options);\n overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);\n }\n\n /**\n * {@link OnHttpListener}\n */\n\n @Override\n public void onStart(Call call) {\n showDialog();\n }\n\n @Override\n public void onSucceed(Object result) {\n if (result instanceof HttpData) {\n toast(((HttpData<?>) result).getMessage());\n }\n }\n\n @Override\n public void onFail(Exception e) {\n toast(e.getMessage());\n }\n\n @Override\n public void onEnd(Call call) {\n hideDialog();\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (isShowDialog()) {\n hideDialog();\n }\n mDialog = null;\n }\n}" }, { "identifier": "GetCodeApi", "path": "app/src/main/java/com/buaa/food/http/api/GetCodeApi.java", "snippet": "public final class GetCodeApi implements IRequestApi {\n\n @Override\n public String getApi() {\n return \"code/get\";\n }\n\n /** 手机号 */\n private String phone;\n\n public GetCodeApi setPhone(String phone) {\n this.phone = phone;\n return this;\n }\n}" }, { "identifier": "PhoneApi", "path": "app/src/main/java/com/buaa/food/http/api/PhoneApi.java", "snippet": "public final class PhoneApi implements IRequestApi {\n\n @Override\n public String getApi() {\n return \"user/phone\";\n }\n\n /** 旧手机号验证码(没有绑定情况下可不传) */\n private String preCode;\n\n /** 新手机号 */\n private String phone;\n /** 新手机号验证码 */\n private String code;\n\n public PhoneApi setPreCode(String preCode) {\n this.preCode = preCode;\n return this;\n }\n\n public PhoneApi setPhone(String phone) {\n this.phone = phone;\n return this;\n }\n\n public PhoneApi setCode(String code) {\n this.code = code;\n return this;\n }\n}" }, { "identifier": "HttpData", "path": "app/src/main/java/com/buaa/food/http/model/HttpData.java", "snippet": "public class HttpData<T> {\n\n /** 返回码 */\n private int code;\n /** 提示语 */\n private String msg;\n /** 数据 */\n private T data;\n\n public int getCode() {\n return code;\n }\n\n public String getMessage() {\n return msg;\n }\n\n public T getData() {\n return data;\n }\n\n /**\n * 是否请求成功\n */\n public boolean isRequestSucceed() {\n return code == 200;\n }\n\n /**\n * 是否 Token 失效\n */\n public boolean isTokenFailure() {\n return code == 1001;\n }\n}" }, { "identifier": "InputTextManager", "path": "app/src/main/java/com/buaa/food/manager/InputTextManager.java", "snippet": "public final class InputTextManager implements TextWatcher {\n\n /** 操作按钮的View */\n private final View mView;\n /** 是否禁用后设置半透明度 */\n private final boolean mAlpha;\n\n /** TextView集合 */\n private List<TextView> mViewSet;\n\n /** 输入监听器 */\n @Nullable\n private OnInputTextListener mListener;\n\n /**\n * 构造函数\n *\n * @param view 跟随 TextView 输入为空来判断启动或者禁用这个 View\n * @param alpha 是否需要设置透明度\n */\n private InputTextManager(View view, boolean alpha) {\n if (view == null) {\n throw new IllegalArgumentException(\"are you ok?\");\n }\n mView = view;\n mAlpha = alpha;\n }\n\n /**\n * 创建 Builder\n */\n public static Builder with(Activity activity) {\n return new Builder(activity);\n }\n\n /**\n * 添加 TextView\n *\n * @param views 传入单个或者多个 TextView\n */\n public void addViews(List<TextView> views) {\n if (views == null) {\n return;\n }\n\n if (mViewSet == null) {\n mViewSet = views;\n } else {\n mViewSet.addAll(views);\n }\n\n for (TextView view : views) {\n view.addTextChangedListener(this);\n }\n\n // 触发一次监听\n notifyChanged();\n }\n\n /**\n * 添加 TextView\n *\n * @param views 传入单个或者多个 TextView\n */\n public void addViews(TextView... views) {\n if (views == null) {\n return;\n }\n\n if (mViewSet == null) {\n mViewSet = new ArrayList<>(views.length);\n }\n\n for (TextView view : views) {\n // 避免重复添加\n if (!mViewSet.contains(view)) {\n view.addTextChangedListener(this);\n mViewSet.add(view);\n }\n }\n // 触发一次监听\n notifyChanged();\n }\n\n /**\n * 移除 TextView 监听,避免内存泄露\n */\n public void removeViews(TextView... views) {\n if (mViewSet == null || mViewSet.isEmpty()) {\n return;\n }\n\n for (TextView view : views) {\n view.removeTextChangedListener(this);\n mViewSet.remove(view);\n }\n // 触发一次监听\n notifyChanged();\n }\n\n /**\n * 移除所有 TextView 监听,避免内存泄露\n */\n public void removeAllViews() {\n if (mViewSet == null) {\n return;\n }\n\n for (TextView view : mViewSet) {\n view.removeTextChangedListener(this);\n }\n mViewSet.clear();\n mViewSet = null;\n }\n\n /**\n * 设置输入监听\n */\n public void setListener(@Nullable OnInputTextListener listener) {\n mListener = listener;\n }\n\n /**\n * {@link TextWatcher}\n */\n\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {}\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {}\n\n @Override\n public void afterTextChanged(Editable s) {\n notifyChanged();\n }\n\n /**\n * 通知更新\n */\n public void notifyChanged() {\n if (mViewSet == null) {\n return;\n }\n\n // 重新遍历所有的输入\n for (TextView view : mViewSet) {\n if (\"\".equals(view.getText().toString())) {\n setEnabled(false);\n return;\n }\n }\n\n if (mListener == null) {\n setEnabled(true);\n return;\n }\n\n setEnabled(mListener.onInputChange(this));\n }\n\n /**\n * 设置 View 的事件\n *\n * @param enabled 启用或者禁用 View 的事件\n */\n public void setEnabled(boolean enabled) {\n if (enabled == mView.isEnabled()) {\n return;\n }\n\n if (enabled) {\n //启用View的事件\n mView.setEnabled(true);\n if (mAlpha) {\n //设置不透明\n mView.setAlpha(1f);\n }\n } else {\n //禁用View的事件\n mView.setEnabled(false);\n if (mAlpha) {\n //设置半透明\n mView.setAlpha(0.5f);\n }\n }\n }\n\n public static final class Builder {\n\n /** 当前的 Activity */\n private final Activity mActivity;\n /** 操作按钮的 View */\n private View mView;\n /** 是否禁用后设置半透明度 */\n private boolean isAlpha;\n /** TextView集合 */\n private final List<TextView> mViewSet = new ArrayList<>();\n /** 输入变化监听 */\n private OnInputTextListener mListener;\n\n private Builder(@NonNull Activity activity) {\n mActivity = activity;\n }\n\n public Builder addView(TextView view) {\n mViewSet.add(view);\n return this;\n }\n\n public Builder setMain(View view) {\n mView = view;\n return this;\n }\n\n public Builder setAlpha(boolean alpha) {\n isAlpha = alpha;\n return this;\n }\n\n public Builder setListener(OnInputTextListener listener) {\n mListener = listener;\n return this;\n }\n\n public InputTextManager build() {\n InputTextManager helper = new InputTextManager(mView, isAlpha);\n helper.addViews(mViewSet);\n helper.setListener(mListener);\n TextInputLifecycle.register(mActivity, helper);\n return helper;\n }\n }\n\n private static class TextInputLifecycle implements Application.ActivityLifecycleCallbacks {\n\n private Activity mActivity;\n private InputTextManager mTextHelper;\n\n private TextInputLifecycle(Activity activity, InputTextManager helper) {\n mActivity = activity;\n mTextHelper = helper;\n }\n\n private static void register(Activity activity, InputTextManager helper) {\n TextInputLifecycle lifecycle = new TextInputLifecycle(activity, helper);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n activity.registerActivityLifecycleCallbacks(lifecycle);\n } else {\n activity.getApplication().registerActivityLifecycleCallbacks(lifecycle);\n }\n }\n\n @Override\n public void onActivityCreated(@NonNull Activity activity, Bundle savedInstanceState) {}\n\n @Override\n public void onActivityStarted(@NonNull Activity activity) {}\n\n @Override\n public void onActivityResumed(@NonNull Activity activity) {}\n\n @Override\n public void onActivityPaused(@NonNull Activity activity) {}\n\n @Override\n public void onActivityStopped(@NonNull Activity activity) {}\n\n @Override\n public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}\n\n @Override\n public void onActivityDestroyed(@NonNull Activity activity) {\n if (mActivity != activity) {\n return;\n }\n mTextHelper.removeAllViews();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n mActivity.unregisterActivityLifecycleCallbacks(this);\n } else {\n mActivity.getApplication().unregisterActivityLifecycleCallbacks(this);\n }\n mTextHelper = null;\n mActivity = null;\n }\n }\n\n /**\n * 文本变化监听器\n */\n public interface OnInputTextListener {\n\n /**\n * 输入发生了变化\n *\n * @return 返回按钮的 Enabled 状态\n */\n boolean onInputChange(InputTextManager manager);\n }\n}" }, { "identifier": "TipsDialog", "path": "app/src/main/java/com/buaa/food/ui/dialog/TipsDialog.java", "snippet": "public final class TipsDialog {\n\n public final static int ICON_FINISH = R.drawable.tips_finish_ic;\n public final static int ICON_ERROR = R.drawable.tips_error_ic;\n public final static int ICON_WARNING = R.drawable.tips_warning_ic;\n\n public static final class Builder\n extends BaseDialog.Builder<Builder>\n implements Runnable, BaseDialog.OnShowListener {\n\n private final TextView mMessageView;\n private final ImageView mIconView;\n\n private int mDuration = 2000;\n\n public Builder(Context context) {\n super(context);\n setContentView(R.layout.tips_dialog);\n setAnimStyle(BaseDialog.ANIM_TOAST);\n setBackgroundDimEnabled(false);\n setCancelable(false);\n\n mMessageView = findViewById(R.id.tv_tips_message);\n mIconView = findViewById(R.id.iv_tips_icon);\n\n addOnShowListener(this);\n }\n\n public Builder setIcon(@DrawableRes int id) {\n mIconView.setImageResource(id);\n return this;\n }\n\n public Builder setDuration(int duration) {\n mDuration = duration;\n return this;\n }\n\n public Builder setMessage(@StringRes int id) {\n return setMessage(getString(id));\n }\n public Builder setMessage(CharSequence text) {\n mMessageView.setText(text);\n return this;\n }\n\n @Override\n public BaseDialog create() {\n // 如果显示的图标为空就抛出异常\n if (mIconView.getDrawable() == null) {\n throw new IllegalArgumentException(\"The display type must be specified\");\n }\n // 如果内容为空就抛出异常\n if (TextUtils.isEmpty(mMessageView.getText().toString())) {\n throw new IllegalArgumentException(\"Dialog message not null\");\n }\n\n return super.create();\n }\n\n @Override\n public void onShow(BaseDialog dialog) {\n // 延迟自动关闭\n postDelayed(this, mDuration);\n }\n\n @Override\n public void run() {\n if (!isShowing()) {\n return;\n }\n dismiss();\n }\n }\n}" }, { "identifier": "CountdownView", "path": "library/widget/src/main/java/com/hjq/widget/view/CountdownView.java", "snippet": "public final class CountdownView extends AppCompatTextView implements Runnable {\n\n /** 倒计时秒数 */\n private int mTotalSecond = 60;\n /** 秒数单位文本 */\n private static final String TIME_UNIT = \"S\";\n\n /** 当前秒数 */\n private int mCurrentSecond;\n /** 记录原有的文本 */\n private CharSequence mRecordText;\n\n public CountdownView(Context context) {\n super(context);\n }\n\n public CountdownView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n }\n\n public CountdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n /**\n * 设置倒计时总秒数\n */\n public void setTotalTime(int totalTime) {\n this.mTotalSecond = totalTime;\n }\n\n /**\n * 开始倒计时\n */\n public void start() {\n mRecordText = getText();\n setEnabled(false);\n mCurrentSecond = mTotalSecond;\n post(this);\n }\n\n /**\n * 结束倒计时\n */\n public void stop() {\n mCurrentSecond = 0;\n setText(mRecordText);\n setEnabled(true);\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n // 移除延迟任务,避免内存泄露\n removeCallbacks(this);\n }\n\n @SuppressLint(\"SetTextI18n\")\n @Override\n public void run() {\n if (mCurrentSecond == 0) {\n stop();\n return;\n }\n mCurrentSecond--;\n setText(mCurrentSecond + \" \" + TIME_UNIT);\n postDelayed(this, 1000);\n }\n}" } ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.KeyEvent; import android.view.View; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.buaa.food.R; import com.buaa.food.aop.Log; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.http.api.GetCodeApi; import com.buaa.food.http.api.PhoneApi; import com.buaa.food.http.model.HttpData; import com.buaa.food.manager.InputTextManager; import com.buaa.food.ui.dialog.TipsDialog; import com.hjq.http.EasyHttp; import com.hjq.http.listener.HttpCallback; import com.hjq.toast.ToastUtils; import com.hjq.widget.view.CountdownView;
5,317
package com.buaa.food.ui.activity; public final class PhoneResetActivity extends AppActivity implements TextView.OnEditorActionListener { private static final String INTENT_KEY_IN_CODE = "code"; @Log public static void start(Context context, String code) { Intent intent = new Intent(context, PhoneResetActivity.class); intent.putExtra(INTENT_KEY_IN_CODE, code); if (!(context instanceof Activity)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } context.startActivity(intent); } private EditText mPhoneView; private EditText mCodeView; private CountdownView mCountdownView; private Button mCommitView; /** 验证码 */ private String mVerifyCode; @Override protected int getLayoutId() { return R.layout.phone_reset_activity; } @Override protected void initView() { mPhoneView = findViewById(R.id.et_phone_reset_phone); mCodeView = findViewById(R.id.et_phone_reset_code); mCountdownView = findViewById(R.id.cv_phone_reset_countdown); mCommitView = findViewById(R.id.btn_phone_reset_commit); setOnClickListener(mCountdownView, mCommitView); mCodeView.setOnEditorActionListener(this);
package com.buaa.food.ui.activity; public final class PhoneResetActivity extends AppActivity implements TextView.OnEditorActionListener { private static final String INTENT_KEY_IN_CODE = "code"; @Log public static void start(Context context, String code) { Intent intent = new Intent(context, PhoneResetActivity.class); intent.putExtra(INTENT_KEY_IN_CODE, code); if (!(context instanceof Activity)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } context.startActivity(intent); } private EditText mPhoneView; private EditText mCodeView; private CountdownView mCountdownView; private Button mCommitView; /** 验证码 */ private String mVerifyCode; @Override protected int getLayoutId() { return R.layout.phone_reset_activity; } @Override protected void initView() { mPhoneView = findViewById(R.id.et_phone_reset_phone); mCodeView = findViewById(R.id.et_phone_reset_code); mCountdownView = findViewById(R.id.cv_phone_reset_countdown); mCommitView = findViewById(R.id.btn_phone_reset_commit); setOnClickListener(mCountdownView, mCommitView); mCodeView.setOnEditorActionListener(this);
InputTextManager.with(this)
4
2023-11-14 10:04:26+00:00
8k
WallasAR/GUITest
src/main/java/com/example/guitest/MedController.java
[ { "identifier": "Banco", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStatement();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public static Connection conexao(){\n Connection conn = null;\n String url = \"jdbc:mysql://localhost:3306/farmacia?serverTimezone=America/Sao_Paulo\";\n String user = \"adm\";\n String password = \"1234\";\n try {\n conn = DriverManager.getConnection(url, user, password);\n\n } catch (SQLException erro) {\n JOptionPane.showMessageDialog(null, erro.getMessage());\n }\n return conn;\n }\n public void criartabela(){\n try {\n if(!tabelaExiste(\"medicamentos\")) {\n executar.execute(\"CREATE TABLE medicamentos(id INT NOT NULL AUTO_INCREMENT ,nome VARCHAR(25), quantidade INT, tipo VARCHAR(25), valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public static void deletarcliente(String idcli) throws SQLException{\n Connection connection = conexao();\n String deletecli = (\"DELETE FROM cliente WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(deletecli);\n preparedStatement.setString(1, idcli);\n preparedStatement.executeUpdate();\n }\n private boolean tabelaExiste(String nomeTabela) throws SQLException {\n // Verificar se a tabela já existe no banco de dados\n try (Connection connection = conexao();\n ResultSet resultSet = connection.getMetaData().getTables(null, null, nomeTabela, null)) {\n return resultSet.next();\n }\n }\n public void autenticar(){\n try {\n if(!tabelaExiste(\"autenticar\")) {\n executar.execute(\"CREATE TABLE autenticar(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), password VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public void inseriradm(String user, String pass){\n try{\n String adm = (\"INSERT INTO autenticar (usuario, password) VALUES (?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(adm);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, pass);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void tablecliete(){\n try{\n if(!tabelaExiste(\"cliente\")){\n executar.execute(\"CREATE TABLE cliente(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), telefone VARCHAR(30), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public static boolean verificarusuario(String user){\n boolean existe = false;\n Connection connection = conexao();\n try{\n String verificar = \"SELECT * FROM cliente WHERE usuario = ?\";\n try(PreparedStatement verificarexis = connection.prepareStatement(verificar)){\n verificarexis.setString(1, user);\n try(ResultSet verificarresultado = verificarexis.executeQuery()){\n existe = verificarresultado.next();\n }\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n return existe;\n }\n public void inserircliente(String nomecli, String sobrenomecli, String user, String fone){\n try{\n if(verificarusuario(user)) {\n AlertMsg alert = new AlertMsg();\n alert.msgInformation(\"Erro ao registrar\" , \"Nome de usuário ja está sendo utilizado, tente novamente.\");\n }else{\n String cliente = (\"INSERT INTO cliente (nome, sobrenome, usuario, telefone) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nomecli);\n preparedStatement.setString(2, sobrenomecli);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, fone);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public void updateClient(String nome, String sobrenome, String usuario, String fone, String idcli) throws SQLException {\n String updateQuaryCli = \"UPDATE cliente SET nome = ?, sobrenome = ?, usuario = ?, telefone = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, usuario);\n preparedStatement.setString(4, fone);\n preparedStatement.setString(5, idcli);\n preparedStatement.executeUpdate();\n }\n\n public void inserirmedicamento(String nomMedi, int quantiMedi,String tipoMedi, float valorMedi ){\n try{\n String medi = (\"INSERT INTO medicamentos (nome, quantidade, tipo , valor) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(medi);\n preparedStatement.setString(1, nomMedi);\n preparedStatement.setInt(2, quantiMedi);\n preparedStatement.setString(3, tipoMedi);\n preparedStatement.setFloat(4, valorMedi);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public static int somarentidadeseliente() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM cliente\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSoma = statement.executeQuery()) {\n\n if (consultaSoma.next()) {\n int soma = consultaSoma.getInt(\"soma_total\");\n return soma;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesefuncionarios() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM funcionarios\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomafu = statement.executeQuery()) {\n\n if (consultaSomafu.next()) {\n int somafu = consultaSomafu.getInt(\"soma_total\");\n return somafu;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesmedicamentos() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM medicamentos\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomamedi = statement.executeQuery()) {\n\n if (consultaSomamedi.next()) {\n int somamedi = consultaSomamedi.getInt(\"soma_total\");\n return somamedi;\n //System.out.println(\"Soma total de Medicamentos registrados: \" + somamedi);\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n\n public void tabelafuncionario(){\n try {\n if(!tabelaExiste(\"funcionarios\")) {\n executar.execute(\"CREATE TABLE funcionarios(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), cargo VARCHAR(25), cpf VARCHAR(25), salario FLOAT, senha VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirfuncinario(String nome, String sobrenome, String user, String cargo, String Cpf, float salario, String senha){\n try{\n if(verificarusuario(user)) {\n System.out.println(\"O nome de usuario não pode ser utilizado, tente outro.\");\n }else{\n String cliente = (\"INSERT INTO funcionarios (nome, sobrenome, usuario, cargo, cpf, salario, senha) VALUES(?,?,?,?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, Cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void updateFuncionario(String nome, String sobrenome, String user, String cargo, String cpf, float salario, String senha, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE funcionarios SET nome = ?, sobrenome = ?, usuario = ?, cargo = ?, cpf = ?, salario = ?, senha = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n preparedStatement.setInt(8,idfunc);\n preparedStatement.executeUpdate();\n }\n public static void deletarfuncionario(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM funcionarios WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public static void deletarmedicamento(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM medicamentos WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public void updateMedicamento(String nome, int quantidade, String tipo, float valor, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE medicamentos SET nome = ?, quantidade = ?, tipo = ?, valor = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setInt(2, quantidade);\n preparedStatement.setString(3, tipo);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setInt(5,idfunc);\n preparedStatement.executeUpdate();\n }\n public void registro(){\n try {\n if(!tabelaExiste(\"registros\")) {\n executar.execute(\"CREATE TABLE registros(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, data VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n\n public void inseriregistro(String user, String medicamento, int quantidade, float valor, String date) throws SQLException {\n String dados = (\"INSERT INTO registros (usuario, medicamento, quantidade, valor, data) VALUES (?, ?, ?,?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, date);\n\n preparedStatement.executeUpdate();\n }\n public void carrinho(){\n try {\n if(!tabelaExiste(\"carrinho\")) {\n executar.execute(\"CREATE TABLE carrinho(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserircarrinho(String user, String medicamento, int quantidade, float valor) throws SQLException {\n String dados = (\"INSERT INTO carrinho (usuario, medicamento, quantidade, valor) VALUES (?, ?, ?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n\n preparedStatement.executeUpdate();\n }\n public void encomendas(){\n try {\n if(!tabelaExiste(\"encomendas\")) {\n executar.execute(\"CREATE TABLE encomendas(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor INT, data VARCHAR(50), telefone VARCHAR(50), status VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirencomendas(String user, String medicamento, int quantidade, float valor, String data,String fone, String status) throws SQLException {\n String dados = (\"INSERT INTO encomendas (usuario, medicamento, quantidade, valor, telefone, data, status) VALUES (?, ?, ?, ?, ?, ?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, fone);\n preparedStatement.setString(6, data);\n preparedStatement.setString(7, status);\n\n preparedStatement.executeUpdate();\n }\n}" }, { "identifier": "FuncionarioTable", "path": "src/main/java/com/table/view/FuncionarioTable.java", "snippet": "public class FuncionarioTable {\n private int id;\n private String nome;\n private String sobrenome;\n private String user;\n private String cargo;\n private String cpf;\n private float salario;\n private String pass;\n\n public FuncionarioTable(int id, String nome, String sobrenome, String user, String cargo, String cpf, float salario, String pass) {\n this.id = id;\n this.nome = nome;\n this.sobrenome = sobrenome;\n this.user = user;\n this.cargo = cargo;\n this.cpf = cpf;\n this.salario = salario;\n this.pass = pass;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getNome() {\n return nome;\n }\n\n public void setNome(String nome) {\n this.nome = nome;\n }\n\n public String getSobrenome() {\n return sobrenome;\n }\n\n public void setSobrenome(String sobrenome) {\n this.sobrenome = sobrenome;\n }\n\n public String getCargo() {\n return cargo;\n }\n\n public void setCargo(String cargo) {\n this.cargo = cargo;\n }\n\n public String getCpf() {\n return cpf;\n }\n\n public void setCpf(String cpf) {\n cpf = cpf;\n }\n\n public float getSalario() {\n return salario;\n }\n\n public void setSalario(float salario) {\n this.salario = salario;\n }\n\n public String getUser() {\n return user;\n }\n\n public void setUser(String user) {\n this.user = user;\n }\n\n public String getPass() {\n return pass;\n }\n\n public void setPass(String pass) {\n this.pass = pass;\n }\n}" }, { "identifier": "MedicamentoTable", "path": "src/main/java/com/table/view/MedicamentoTable.java", "snippet": "public class MedicamentoTable {\n private int id;\n private String nomemedi;\n private int quantidade;\n private String tipo;\n private float valor;\n\n public MedicamentoTable(int id, String nomemedi, int quantidade, String tipo, float valor) {\n this.id = id;\n this.nomemedi = nomemedi;\n this.quantidade = quantidade;\n this.tipo = tipo;\n this.valor = valor;\n }\n\n public String getNomemedi() {\n return nomemedi;\n }\n\n public void setNomemedi(String nomemedi) {\n this.nomemedi = nomemedi;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getQuantidade() {\n return quantidade;\n }\n\n public void setQuantidade(int quantidade) {\n this.quantidade = quantidade;\n }\n\n public String getTipo() {\n return tipo;\n }\n\n public void setTipo(String tipo) {\n this.tipo = tipo;\n }\n\n public float getValor() {\n return valor;\n }\n\n public void setValor(float valor) {\n this.valor = valor;\n }\n}" }, { "identifier": "AlertMsg", "path": "src/main/java/com/warning/alert/AlertMsg.java", "snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}" }, { "identifier": "connection", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public static Connection connection = conexao();" } ]
import com.db.bank.Banco; import com.table.view.FuncionarioTable; import com.table.view.MedicamentoTable; import com.warning.alert.AlertMsg; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.fxml.FXML; import static com.db.bank.Banco.connection; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle;
4,770
package com.example.guitest; public class MedController implements Initializable { Banco banco = new Banco(); @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout", "Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void HomeAction(MouseEvent e) { Main.changedScene("home"); } @FXML protected void FuncAction(MouseEvent e) { Main.changedScene("func"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("client"); } @FXML protected void RecordAction(MouseEvent e) { Main.changedScene("record"); } @FXML private TableView tbMedicamento; @FXML private TableColumn clIdmedi; @FXML private TableColumn clNomemedi; @FXML private TableColumn clQuantimedi; @FXML private TableColumn clTipomedi; @FXML private TableColumn clPreçomedi; @FXML private TextField tfSearch; @FXML private TextField tfNome; @FXML private TextField tfQuantidade; @FXML private TextField tfTipo; @FXML private TextField tfValor; @FXML private TextField tfId; public void tabelamedi() throws SQLException { List<MedicamentoTable> medicamentos = new ArrayList<>(); String consultaSQL = "SELECT * FROM medicamentos";
package com.example.guitest; public class MedController implements Initializable { Banco banco = new Banco(); @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout", "Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void HomeAction(MouseEvent e) { Main.changedScene("home"); } @FXML protected void FuncAction(MouseEvent e) { Main.changedScene("func"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("client"); } @FXML protected void RecordAction(MouseEvent e) { Main.changedScene("record"); } @FXML private TableView tbMedicamento; @FXML private TableColumn clIdmedi; @FXML private TableColumn clNomemedi; @FXML private TableColumn clQuantimedi; @FXML private TableColumn clTipomedi; @FXML private TableColumn clPreçomedi; @FXML private TextField tfSearch; @FXML private TextField tfNome; @FXML private TextField tfQuantidade; @FXML private TextField tfTipo; @FXML private TextField tfValor; @FXML private TextField tfId; public void tabelamedi() throws SQLException { List<MedicamentoTable> medicamentos = new ArrayList<>(); String consultaSQL = "SELECT * FROM medicamentos";
Statement statement = connection.createStatement();
4
2023-11-16 14:55:08+00:00
8k
wzh933/Buffer-Manager
src/main/java/cs/adb/wzh/dataStorageManager/DSMgr.java
[ { "identifier": "Buffer", "path": "src/main/java/cs/adb/wzh/Storage/Buffer.java", "snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n }\n\n\n public Buffer() {\n final int DEF_BUF_SIZE = 1024;\n this.bufSize = DEF_BUF_SIZE;\n this.buf = new Frame[DEF_BUF_SIZE];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n /**\n * @param bufSize:用户自定义的缓存区大小\n */\n public Buffer(int bufSize) throws Exception {\n if (bufSize <= 0) {\n throw new Exception(\"缓存区大小不可以为非正数!\");\n }\n this.bufSize = bufSize;\n this.buf = new Frame[bufSize];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n public Frame readFrame(int frameId) {\n return buf[frameId];\n }\n\n public void writeFrame(Page page, int frameId) {\n //先不进行任何操作\n }\n\n}" }, { "identifier": "Disk", "path": "src/main/java/cs/adb/wzh/Storage/Disk.java", "snippet": "public class Disk {\n private final int diskSize;\n private final Page[] disk;\n\n public int getDiskSize() {\n return diskSize;\n }\n\n public Page[] getDisk() {\n return disk;\n }\n\n\n public Disk() {\n final int DEF_BUF_SIZE = 65536;//256MB的磁盘\n this.diskSize = DEF_BUF_SIZE;\n this.disk = new Page[DEF_BUF_SIZE];\n //初始化磁盘空间\n for (int pageId = 0; pageId < this.diskSize; pageId++) {\n this.disk[pageId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "File", "path": "src/main/java/cs/adb/wzh/Storage/File.java", "snippet": "public class File {\n private final int fileSize;\n private final Page[] records;\n\n public int getFileSize() {\n return fileSize;\n }\n\n public Page getFileRecord(int recordId) {\n return records[recordId];\n }\n\n\n public File(String filename) {\n final int DEF_FILE_SIZE = 50000;//50000个页面的文件\n this.fileSize = DEF_FILE_SIZE;\n this.records = new Page[DEF_FILE_SIZE];\n //假设可以读取这个文件,实际上只是初始化文件空间\n for (int recordId = 0; recordId < this.fileSize; recordId++) {\n this.records[recordId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "Frame", "path": "src/main/java/cs/adb/wzh/StorageForm/Frame.java", "snippet": "public class Frame {\n private final int FRAME_SIZE = 4096;\n private char[] field;\n\n public int getFrameSize() {\n return FRAME_SIZE;\n }\n\n public void setField(char[] field) {\n this.field = field;\n }\n\n public char[] getField() {\n return field;\n }\n\n public Frame() {\n this.field = new char[this.FRAME_SIZE];\n }\n}" }, { "identifier": "Page", "path": "src/main/java/cs/adb/wzh/StorageForm/Page.java", "snippet": "public class Page {\n private final int PAGE_SIZE = 4096;\n private char[] field;\n\n public int getFrameSize() {\n return PAGE_SIZE;\n }\n\n public void setField(char[] field) {\n this.field = field;\n }\n\n public char[] getField() {\n return field;\n }\n\n public Page() {\n this.field = new char[this.PAGE_SIZE];\n }\n}" }, { "identifier": "BMgr", "path": "src/main/java/cs/adb/wzh/bufferManager/BMgr.java", "snippet": "public class BMgr {\n private final DSMgr dsMgr;\n private final Bucket[] p2f;\n /*\n 有了BCB表之后就不需要f2p索引表了\n 其中bcbTable[frameId] = BCB(frameId)\n */\n private final BCB[] bcbTable;\n private BCB head;\n private BCB tail;\n private final int bufSize;\n private int freePageNum;\n private final Buffer bf;\n private final Disk disk;\n\n private double hitNum = 0;\n private int operation;//0-读 1-写\n// private BCB freePageTail;\n\n //对页面的读写操作(operation, pageId)\n// private final pageRecordReader pageRecords;\n\n private BCB clockSentinel;//维护一个时钟哨兵\n // private boolean useLRU = false;\n// private boolean useCLOCK = false;\n private SwapMethod swapMethod;\n\n public BMgr(Buffer bf, Disk disk) throws IOException {\n this.bf = bf;\n this.disk = disk;\n this.bufSize = bf.getBufSize();\n this.freePageNum = bufSize;\n\n this.dsMgr = new DSMgr(bf, disk);\n this.dsMgr.openFile(\"data.dbf\");\n\n// this.pageRecords = new pageRecordReader(pageRequestsFilePath);\n\n this.bcbTable = new BCB[bufSize];\n this.p2f = new Bucket[bufSize];\n\n this.head = new BCB(-1);//增加一个frameId为-1的无效节点并在之后作为环形链表的尾结点\n BCB p = this.head, q;\n //初始化帧缓存区BCB的双向循环链表\n for (int i = 0; i < this.bufSize; i++) {\n q = new BCB(i);\n p.setNext(q);//设置后继节点\n q.setPre(p);//设置前驱节点\n p = q;\n if (i == this.bufSize - 1) {\n this.tail = q;//设置缓存区尾指针\n }\n this.bcbTable[i] = p;//bcbTable中: bcbId = bcb.getFrameId()\n }\n //循环链表\n this.head.setPre(tail);\n this.tail.setNext(head);\n //让无效结点作为尾部结点\n this.head = this.head.getNext();\n this.tail = this.tail.getNext();\n }\n\n public BCB getHead() {\n return head;\n }\n\n public BCB getTail() {\n return tail;\n }\n\n public BCB[] getBcbTable() {\n return bcbTable;\n }\n\n\n public void move2Head(BCB bcb) {\n if (bcb == this.head || bcb == this.tail) {\n /*\n 本就是首尾部结点则不做任何操作\n 因为首部结点不用动\n 尾部结点无效也不需要任何操作\n */\n return;\n }\n //这样写代码舒服多了\n bcb.getPre().setNext(bcb.getNext());\n bcb.getNext().setPre(bcb.getPre());\n bcb.setPre(this.tail);\n bcb.setNext(this.head);\n this.head.setPre(bcb);\n this.tail.setNext(bcb);\n this.head = bcb;\n }\n\n\n/*\n /**\n * 文件和访问管理器将使用记录的record_id中的page_id调用这个页面\n * 该函数查看页面是否已经在缓冲区中\n * 如果是,则返回相应的frame_id\n * 如果页面尚未驻留在缓冲区中,则它会选择牺牲页面(如果需要),并加载所请求的页面。\n *\n * @param pageId:需要被固定于缓存区的页号\n * @return frameId:页面pageId被固定于缓存区的帧号\n * /\n public int fixPage(int pageId) throws Exception {\n int frameId = this.fixPageLRU(pageId);//可以切换不同的策略进行页面的置换\n this.bcbTable[frameId].setDirty(operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n\n return frameId;\n/*\n Page page = this.dsMgr.readPage(pageId);\n if (this.p2f[this.hash(pageId)] == null) {//如果pageId对应的hash桶是空的则新建桶\n this.p2f[this.hash(pageId)] = new Bucket();\n }\n Bucket hashBucket = this.p2f[this.hash(pageId)];//找到pageId可能存放的hash桶\n BCB targetBCB = hashBucket.searchPage(pageId);//寻找hash桶中的页面\n if (targetBCB != null) {\n /*\n 如果该页面存放在缓存区中\n 那么命中次数加一\n 同时将该页面置于循环链表的首部\n * /\n this.hitNum++;\n this.move2Head(targetBCB);\n return targetBCB.getFrameId();\n }\n\n /*\n 如果该页面不在缓存区中,则从磁盘读取该页并且执行如下的内存操作:\n a)该缓存区未满,则将该页面存放于缓存区的尾部并将其移动至首部\n b)该缓存区已满,则执行淘汰规则:\n 1、得到需要将要被置换(牺牲)的尾部页面victimBCB和其帧号frameId\n 2、将victimBCB从其原来的pageId对应的hash桶中删除\n 3、修改victimBCB原来的pageId为当前pageId\n 4、将victimBCB放入当前pageId对应的hash桶中\n 5、将victimBCB移到首部\n 6、如果该帧脏位为1,则将帧frameId中的内容写入页面pageId中\n * /\n this.dsMgr.readPage(pageId);\n int frameId;\n if (this.freePageNum > 0) {\n frameId = this.bufSize - this.freePageNum;\n BCB freeBCB = this.bcbTable[frameId];\n freeBCB.setPageId(pageId);\n this.move2Head(freeBCB);\n this.freePageNum--;\n this.p2f[this.hash(freeBCB.getPageId())].appendBCB(freeBCB);\n } else {\n frameId = this.selectVictim();\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n BCB victimBCB = this.bcbTable[frameId];\n victimBCB.setPageId(pageId);\n// System.out.printf(\"frameId: %d, pageId: %d\\n\", victimBCB.getFrameId(), victimBCB.getPageId());\n hashBucket.appendBCB(victimBCB);\n// this.move2Head(victimBCB);\n\n// this.bf.getBuf()[frameId].setField(page.getField());\n }\n return frameId;\n* /\n\n }\n*/\n\n\n /**\n * 当插入、索引拆分或创建对象时需要一个新页面时,使用这个函数\n * 此函数将找到一个空页面,文件和访问管理器可以使用它来存储一些数据\n *\n * @return 该page被分配到缓存区中的frameId\n */\n public int fixNewPage() throws Exception {\n /*\n 先在被固定的页面中搜索可用位为0的页面\n 如果找到被固定页面中的可用页面pageId\n 那么该页面pageId将被重用\n 同时置该页面的使用位为1\n */\n for (int pageId = 0; pageId < dsMgr.getNumPages(); pageId++) {\n if (dsMgr.getUse(pageId) == 0) {\n dsMgr.setUse(pageId, 1);\n return pageId;\n }\n }\n /*\n 否则被固定的页面计数器+=1\n 并且从非固定页面中重新分配页面\n 并且置该页面的使用位为1\n 其中被分配的页面allocPageId为pageNum(pageId从0开始)\n */\n int allocPageId = dsMgr.getNumPages();\n if (allocPageId >= dsMgr.getMaxPageNum()) {\n throw new Exception(\"当前磁盘已满,无法分配新页面!\");\n }\n dsMgr.setUse(allocPageId, 1);\n dsMgr.incNumPages();\n return allocPageId;\n }\n\n /**\n * 文件和访问管理器将使用记录的record_id中的page_id调用这个页面\n * 该函数查看页面是否已经在缓冲区中\n * 如果是,则返回相应的frame_id\n * 如果页面尚未驻留在缓冲区中,则它会选择牺牲页面(如果需要),并加载所请求的页面。\n *\n * @param pageId:需要被固定于缓存区的页号\n * @return frameId:页面pageId被固定于缓存区的帧号\n */\n public int fixPage(int pageId) throws Exception {\n if (this.p2f[this.hash(pageId)] == null) {//如果pageId对应的hash桶是空的则新建桶\n this.p2f[this.hash(pageId)] = new Bucket();\n }\n Bucket hashBucket = this.p2f[this.hash(pageId)];//找到pageId可能存放的hash桶\n BCB targetBCB = hashBucket.searchPage(pageId);//寻找hash桶中的页面\n if (targetBCB != null) {\n /*\n 如果该页面存放在缓存区中\n 那么命中次数加一\n 如果采用LRU策略则将该页面置于循环链表的首部\n */\n this.hitNum++;\n targetBCB.setDirty(this.operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n if (this.swapMethod == SwapMethod.LRU) {//如果使用LRU置换算法则将命中页面移动至首部\n this.move2Head(targetBCB);\n }\n targetBCB.setReferenced(1);\n return targetBCB.getFrameId();\n }\n\n /*\n 如果该页面不在缓存区中,则从磁盘读取该页并且执行如下的内存操作:\n a)该缓存区未满,则将该页面存放于缓存区的尾部并将其移动至首部\n b)该缓存区已满,则执行淘汰规则:\n 1、得到需要将要被置换(牺牲)的尾部页面victimBCB和其帧号frameId\n 2、将victimBCB从其原来的pageId对应的hash桶中删除\n 3、修改victimBCB原来的pageId为当前pageId\n 4、将victimBCB放入当前pageId对应的hash桶中\n 5、将victimBCB移到首部\n 6、如果该帧脏位为1,则将帧frameId中的内容写入页面pageId中\n */\n if (this.operation == 0) {\n this.dsMgr.readPage(pageId);\n }\n int frameId;\n if (this.freePageNum > 0) {\n frameId = this.bufSize - this.freePageNum;\n BCB freeBCB = this.bcbTable[frameId];\n freeBCB.setPageId(pageId);\n this.move2Head(freeBCB);\n //让时钟哨兵指向循环双向链表中的最后一个结点\n this.clockSentinel = this.tail.getPre();\n// this.clockSentinel = this.head;\n this.freePageNum--;\n this.p2f[this.hash(freeBCB.getPageId())].appendBCB(freeBCB);\n } else {\n frameId = this.selectVictim();\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n BCB victimBCB = this.bcbTable[frameId];\n victimBCB.setPageId(pageId);\n// System.out.printf(\"frameId: %d, pageId: %d\\n\", victimBCB.getFrameId(), victimBCB.getPageId());\n hashBucket.appendBCB(victimBCB);\n// this.move2Head(victimBCB);\n\n// this.bf.getBuf()[frameId].setField(page.getField());\n }\n this.bcbTable[frameId].setDirty(operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n return frameId;\n }\n\n /**\n * NumFreeFrames函数查看缓冲区,并返回可用的缓冲区页数\n *\n * @return int\n */\n public int numFreeFrames() {\n return freePageNum;\n }\n\n /**\n * @return 被淘汰的页面存放的帧号frameId\n */\n private int selectVictim() throws Exception {\n int victimFrame;\n switch (swapMethod) {\n case LRU -> victimFrame = removeLRUEle();\n case CLOCK -> victimFrame = removeCLOCKEle();\n default -> victimFrame = this.tail.getPre().getFrameId();\n }\n return victimFrame;\n }\n\n private int hash(int pageId) {\n return pageId % bufSize;\n }\n\n private void removeBCB(int pageId) throws Exception {\n Bucket hashBucket = this.p2f[this.hash(pageId)];\n if (hashBucket == null) {\n throw new Exception(\"哈希桶不存在,代码出错啦!\");\n }\n if (this.p2f[this.hash(pageId)].searchPage(pageId) == null) {\n throw new Exception(\"找不到要删除的页,代码出错啦!\");\n }\n\n for (Bucket curBucket = hashBucket; curBucket != null; curBucket = curBucket.getNext()) {\n for (int i = 0; i < curBucket.getBcbNum(); i++) {\n if (curBucket.getBcbList().get(i).getPageId() == pageId) {\n curBucket.getBcbList().remove(i);\n// System.out.println(curBucket);\n for (Bucket curBucket1 = curBucket; curBucket1 != null; curBucket1 = curBucket1.getNext()) {\n if (curBucket1.getNext() != null) {\n //将下个桶中的首元素加入当前桶\n curBucket1.getBcbList().add(curBucket1.getNext().getBcbList().get(0));\n //删除下个桶的首元素\n curBucket1.getNext().getBcbList().remove(0);\n //如果下个桶空则删除桶\n if (curBucket1.getNext().getBcbNum() == 0) {\n curBucket1.setNext(null);\n }\n }\n }\n break;\n }\n }\n }\n }\n\n private int removeLRUEle() throws Exception {\n //LRU策略选择尾部结点作为victimBCB\n BCB victimBCB = this.tail.getPre();\n //从hash表中删除BCB并在之后建立新的索引\n this.removeBCB(victimBCB.getPageId());\n //将被淘汰结点放至首部并在之后重新设置其页号\n this.move2Head(victimBCB);\n return victimBCB.getFrameId();\n }\n\n private int removeCLOCKEle() {\n for (; this.clockSentinel.getReferenced() != 0; this.clockSentinel = this.clockSentinel.getNext()) {\n if (this.clockSentinel.getFrameId() == -1) {//遇到无效节点则不进行任何操作\n continue;\n }\n this.clockSentinel.setReferenced(0);\n }\n this.clockSentinel.setReferenced(1);\n int resFrameId = this.clockSentinel.getFrameId();\n this.clockSentinel = this.clockSentinel.getNext();\n if (this.clockSentinel.getFrameId() == -1) {\n this.clockSentinel = this.clockSentinel.getNext();\n }\n return resFrameId;\n }\n\n\n public void writeDirtys() {\n /*\n 这键盘突然好了\n 我真是蚌埠住了\n */\n for (int frameId = 0; frameId < this.bufSize; frameId++) {\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n }\n\n }\n\n public void printBuffer() {\n for (BCB p = this.head; p.getFrameId() != -1; p = p.getNext()) {\n System.out.printf(\"%d, \", p.getPageId());\n }\n System.out.println();\n }\n\n// public void setUseLRU(boolean useLRU) {\n// this.useLRU = useLRU;\n// }\n//\n// public void setUseCLOCK(boolean useCLOCK) {\n// this.useCLOCK = useCLOCK;\n// }\n\n public void setSwapMethod(SwapMethod swapMethod) {\n this.swapMethod = swapMethod;\n }\n\n public double getHitNum() {\n return hitNum;\n }\n\n public void setOperation(int operation) {//0-读 1-写\n this.operation = operation;\n }\n\n public int getReadDiskNum() {\n return this.dsMgr.getReadDiskNum();\n }\n\n public int getWriteDiskNum() {\n return this.dsMgr.getWriteDiskNum();\n }\n\n\n}" } ]
import cs.adb.wzh.Storage.Buffer; import cs.adb.wzh.Storage.Disk; import cs.adb.wzh.Storage.File; import cs.adb.wzh.StorageForm.Frame; import cs.adb.wzh.StorageForm.Page; import cs.adb.wzh.bufferManager.BMgr; import java.io.IOException; import java.util.Arrays;
5,832
package cs.adb.wzh.dataStorageManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class DSMgr { private final int maxPageNum; private int pageNum = 0;//开始时被固定的页面数位0 private final int[] pages; private int curRecordId; private File curFile; private final Buffer bf;
package cs.adb.wzh.dataStorageManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class DSMgr { private final int maxPageNum; private int pageNum = 0;//开始时被固定的页面数位0 private final int[] pages; private int curRecordId; private File curFile; private final Buffer bf;
private final Disk disk;
1
2023-11-15 16:30:06+00:00
8k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/debug/testentity/Zombie/ZombieModelTest.java
[ { "identifier": "AnimationHelper", "path": "src/main/java/useless/dragonfly/helper/AnimationHelper.java", "snippet": "public class AnimationHelper {\n\tpublic static final Map<String, Animation> registeredAnimations = new HashMap<>();\n\n\tpublic static Animation getOrCreateEntityAnimation(String modID, String animationSource) {\n\t\tString animationKey = getAnimationLocation(modID, animationSource);\n\t\tif (registeredAnimations.containsKey(animationKey)){\n\t\t\treturn registeredAnimations.get(animationKey);\n\t\t}\n\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(animationKey))));\n\t\tAnimation animation = DragonFly.GSON.fromJson(reader, Animation.class);\n\t\tregisteredAnimations.put(animationKey, animation);\n\t\treturn animation;\n\t}\n\n\tpublic static String getAnimationLocation(String modID, String animationSource) {\n\t\tif (!animationSource.endsWith(\".json\")) {\n\t\t\tanimationSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + modID + \"/animation/\" + animationSource;\n\t}\n\n\tpublic static void animate(BenchEntityModel entityModel, AnimationData animationData, long time, float scale, Vector3f p_253861_) {\n\t\tfloat seconds = getElapsedSeconds(animationData, time);\n\n\t\tfor (Map.Entry<String, BoneData> entry : animationData.getBones().entrySet()) {\n\t\t\tOptional<BenchEntityBones> optional = entityModel.getAnyDescendantWithName(entry.getKey());\n\t\t\tMap<String, PostData> postionMap = entry.getValue().getPosition();\n\t\t\tList<KeyFrame> positionFrame = Lists.newArrayList();\n\n\t\t\tpostionMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\tpositionFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> positionFrame.forEach((keyFrame2) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, positionFrame.size(), p_232315_ -> seconds <= positionFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(positionFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = positionFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = positionFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame2.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = posVec(positionFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = posVec(positionFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = posVec(positionFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = posVec(positionFrame.get(Math.min(positionFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationPoint(p_232330_.rotationPointX + p_253861_.x, p_232330_.rotationPointY + p_253861_.y, p_232330_.rotationPointZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = posVec(positionFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = posVec(positionFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\t\t\tMap<String, PostData> rotationMap = entry.getValue().getRotation();\n\t\t\tList<KeyFrame> rotationFrame = Lists.newArrayList();\n\n\t\t\trotationMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\trotationFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> rotationFrame.forEach((keyFrame3) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, rotationFrame.size(), p_232315_ -> seconds <= rotationFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(rotationFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = rotationFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = rotationFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame3.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = degreeVec(rotationFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(rotationFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = degreeVec(rotationFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = degreeVec(rotationFrame.get(Math.min(rotationFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationAngle(p_232330_.rotateAngleX + p_253861_.x, p_232330_.rotateAngleY + p_253861_.y, p_232330_.rotateAngleZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = degreeVec(rotationFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(rotationFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\tMap<String, PostData> scaleMap = entry.getValue().getScale();\n\t\t\tList<KeyFrame> scaleFrame = Lists.newArrayList();\n\n\t\t\tscaleMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\tscaleFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> scaleFrame.forEach((keyFrame3) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, scaleFrame.size(), p_232315_ -> seconds <= scaleFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(scaleFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = scaleFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = scaleFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame3.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = degreeVec(scaleFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(scaleFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = degreeVec(scaleFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = degreeVec(scaleFrame.get(Math.min(scaleFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationAngle(p_232330_.rotateAngleX + p_253861_.x, p_232330_.rotateAngleY + p_253861_.y, p_232330_.rotateAngleZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = degreeVec(scaleFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(scaleFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\t\t}\n\t}\n\n\tpublic static float fma(float a, float b, float c) {\n\t\treturn a * b + c;\n\t}\n\n\tprivate static float catmullrom(float p_216245_, float p_216246_, float p_216247_, float p_216248_, float p_216249_) {\n\t\treturn 0.25F\n\t\t\t* (\n\t\t\t2.0F * p_216247_\n\t\t\t\t+ (p_216248_ - p_216246_) * p_216245_\n\t\t\t\t+ (2.0F * p_216246_ - 5.0F * p_216247_ + 4.0F * p_216248_ - p_216249_) * p_216245_ * p_216245_\n\t\t\t\t+ (3.0F * p_216247_ - p_216246_ - 3.0F * p_216248_ + p_216249_) * p_216245_ * p_216245_ * p_216245_\n\t\t);\n\t}\n\n\tprivate static int binarySearch(int startIndex, int endIndex, IntPredicate p_14052_) {\n\t\tint searchSize = endIndex - startIndex;\n\n\t\twhile (searchSize > 0) {\n\t\t\tint j = searchSize / 2;\n\t\t\tint k = startIndex + j;\n\t\t\tif (p_14052_.test(k)) {\n\t\t\t\tsearchSize = j;\n\t\t\t} else {\n\t\t\t\tstartIndex = k + 1;\n\t\t\t\tsearchSize -= j + 1;\n\t\t\t}\n\t\t}\n\n\t\treturn startIndex;\n\t}\n\n\tpublic static Vector3f posVec(float x, float y, float z) {\n\t\treturn new Vector3f(x, -y, z);\n\t}\n\n\tpublic static Vector3f degreeVec(float degX, float degY, float degZ) {\n\t\treturn new Vector3f(degX * (float) (Math.PI / 180.0), degY * (float) (Math.PI / 180.0), degZ * (float) (Math.PI / 180.0));\n\t}\n\n\tpublic static Vector3f posVec(Vector3f vector3f) {\n\t\treturn new Vector3f(vector3f.x, -vector3f.y, vector3f.z);\n\t}\n\n\tpublic static Vector3f degreeVec(Vector3f vector3f) {\n\t\treturn new Vector3f(vector3f.x * (float) (Math.PI / 180.0), vector3f.y * (float) (Math.PI / 180.0), vector3f.z * (float) (Math.PI / 180.0));\n\t}\n\n\tprivate static float getElapsedSeconds(AnimationData animationData, long ms) {\n\t\tfloat seconds = (float) ms / 1000.0F;\n\t\treturn animationData.isLoop() ? seconds % animationData.getAnimationLength() : seconds;\n\t}\n}" }, { "identifier": "BenchEntityModel", "path": "src/main/java/useless/dragonfly/model/entity/BenchEntityModel.java", "snippet": "public class BenchEntityModel extends ModelBase {\n\tpublic Vector3f VEC_ANIMATION = new Vector3f();\n\tprivate final HashMap<String, BenchEntityBones> indexBones = new HashMap<>();\n\t@SerializedName(\"format_version\")\n\tprivate String formatVersion;\n\t@SerializedName(\"minecraft:geometry\")\n\tprivate List<BenchEntityGeometry> benchEntityGeometry;\n\n\tpublic HashMap<String, BenchEntityBones> getIndexBones() {\n\t\treturn indexBones;\n\t}\n\n\t@Override\n\tpublic void render(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {\n\t\tsuper.render(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t\tthis.renderModel(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t}\n\n\tpublic void renderModel(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {\n\t\tBenchEntityGeometry entityGeometry = this.benchEntityGeometry.get(0);\n\n\t\tint texWidth = entityGeometry.getWidth();\n\t\tint texHeight = entityGeometry.getHeight();\n\t\tfor (BenchEntityBones bones : entityGeometry.getBones()) {\n\t\t\tif (!this.getIndexBones().containsKey(bones.getName())) {\n\t\t\t\tthis.getIndexBones().put(bones.getName(), bones);\n\t\t\t}\n\t\t}\n\t\tif (!this.getIndexBones().isEmpty()) {\n\t\t\t//DON'T MOVE IT! because the rotation and rotation position of entities of the same model being mixed.\n\t\t\tthis.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t\t}\n\n\t\tfor (BenchEntityBones bones : entityGeometry.getBones()) {\n\t\t\tString name = bones.getName();\n\t\t\t@Nullable List<Float> rotation = bones.getRotation();\n\t\t\t@Nullable String parent = bones.getParent();\n\n\n\t\t\tif (parent != null) {\n\t\t\t\tif (!this.getIndexBones().get(parent).getChildren().contains(bones)) {\n\t\t\t\t\tthis.getIndexBones().get(parent).addChild(bones);\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tif (bones.getCubes() == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (BenchEntityCube cube : bones.getCubes()) {\n\t\t\t\tList<Float> uv = cube.getUv();\n\t\t\t\tList<Float> size = cube.getSize();\n\t\t\t\t@Nullable List<Float> cubeRotation = cube.getRotation();\n\t\t\t\tboolean mirror = cube.isMirror();\n\t\t\t\tfloat inflate = cube.getInflate();\n\n\t\t\t\tcube.addBox(texWidth, texHeight, convertOrigin(bones, cube, 0), convertOrigin(bones, cube, 1), convertOrigin(bones, cube, 2), false);\n\n\n\t\t\t\tif (!cube.isCompiled()) {\n\t\t\t\t\tcube.compileDisplayList(scale);\n\t\t\t\t}\n\t\t\t\tGL11.glPushMatrix();\n\n\n\t\t\t\t//parent time before rotate it self\n\t\t\t\tif (parent != null) {\n\t\t\t\t\tBenchEntityBones parentBone = this.getIndexBones().get(parent);\n\n\t\t\t\t\tconvertWithMoreParent(parentBone, scale);\n\t\t\t\t}\n\n\t\t\t\tGL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale);\n\n\t\t\t\tif (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) {\n\t\t\t\t\tGL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale);\n\t\t\t\t}\n\t\t\t\tif (rotation != null) {\n\t\t\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f);\n\t\t\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f);\n\t\t\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f);\n\t\t\t\t}\n\n\t\t\t\tif (bones.rotateAngleZ != 0.0f) {\n\t\t\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f);\n\t\t\t\t}\n\t\t\t\tif (bones.rotateAngleY != 0.0f) {\n\t\t\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f);\n\t\t\t\t}\n\t\t\t\tif (bones.rotateAngleX != 0.0f) {\n\t\t\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f);\n\t\t\t\t}\n\n\t\t\t\tif (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) {\n\t\t\t\t\tGL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ);\n\t\t\t\t}\n\n\n\t\t\t\tGL11.glCallList(cube.getDisplayList());\n\n\n\t\t\t\tGL11.glPopMatrix();\n\t\t\t}\n\n\n\t\t}\n\n\t}\n\n\t/*\n\t * This method used Translate for item render\n\t */\n\tpublic void postRender(BenchEntityBones bones, float scale) {\n\t\tList<Float> rotation = bones.getRotation();\n\t\t//parent time before rotate it self\n\t\tif (bones.getParent() != null) {\n\t\t\tBenchEntityBones parentBone = this.getIndexBones().get(bones.getParent());\n\n\t\t\tconvertWithMoreParent(parentBone, scale);\n\t\t}\n\n\t\tGL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale);\n\n\t\tif (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) {\n\t\t\tGL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale);\n\t\t}\n\t\tif (rotation != null) {\n\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f);\n\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f);\n\t\t\tGL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f);\n\t\t}\n\n\t\tif (bones.rotateAngleZ != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f);\n\t\t}\n\t\tif (bones.rotateAngleY != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f);\n\t\t}\n\t\tif (bones.rotateAngleX != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f);\n\t\t}\n\n\t\tif (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) {\n\t\t\tGL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ);\n\t\t}\n\t}\n\n\tprivate void convertWithMoreParent(BenchEntityBones parentBone, float scale) {\n\t\t//don't forget some parent has more parent\n\t\tif (parentBone.getParent() != null) {\n\t\t\tconvertWithMoreParent(this.getIndexBones().get(parentBone.getParent()), scale);\n\t\t}\n\t\tGL11.glTranslatef(convertPivot(parentBone, 0) * scale, convertPivot(parentBone, 1) * scale, convertPivot(parentBone, 2) * scale);\n\n\n\t\tif (parentBone.rotationPointX != 0.0f || parentBone.rotationPointY != 0.0f || parentBone.rotationPointZ != 0.0f) {\n\t\t\tGL11.glTranslatef(parentBone.rotationPointX * scale, parentBone.rotationPointY * scale, parentBone.rotationPointZ * scale);\n\t\t}\n\t\tif (parentBone.getRotation() != null) {\n\t\t\tGL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(0)), 0.0f, 0.0f, 1.0f);\n\t\t\tGL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(1)), 0.0f, 1.0f, 0.0f);\n\t\t\tGL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(2)), 1.0f, 0.0f, 0.0f);\n\t\t}\n\n\t\tif (parentBone.rotateAngleZ != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleZ)), 0.0f, 0.0f, 1.0f);\n\t\t}\n\t\tif (parentBone.rotateAngleY != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleY)), 0.0f, 1.0f, 0.0f);\n\t\t}\n\t\tif (parentBone.rotateAngleX != 0.0f) {\n\t\t\tGL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleX)), 1.0f, 0.0f, 0.0f);\n\t\t}\n\n\t\tif (parentBone.scaleX != 0.0f || parentBone.scaleY != 0.0f || parentBone.scaleZ != 0.0f) {\n\t\t\tGL11.glScalef(parentBone.scaleX, parentBone.scaleY, parentBone.scaleZ);\n\t\t}\n\t}\n\n\tpublic float convertPivot(BenchEntityBones bones, int index) {\n\t\tif (bones.getParent() != null) {\n\t\t\tif (index == 1) {\n\t\t\t\treturn getIndexBones().get(bones.getParent()).getPivot().get(index) - bones.getPivot().get(index);\n\t\t\t} else {\n\t\t\t\treturn bones.getPivot().get(index) - getIndexBones().get(bones.getParent()).getPivot().get(index);\n\t\t\t}\n\t\t} else {\n\t\t\tif (index == 1) {\n\t\t\t\treturn 24 - bones.getPivot().get(index);\n\t\t\t} else {\n\t\t\t\treturn bones.getPivot().get(index);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic float convertPivot(BenchEntityBones parent, BenchEntityCube cube, int index) {\n\t\tassert cube.getPivot() != null;\n\t\tif (index == 1) {\n\t\t\treturn parent.getPivot().get(index) - cube.getPivot().get(index);\n\t\t} else {\n\t\t\treturn cube.getPivot().get(index) - parent.getPivot().get(index);\n\t\t}\n\t}\n\n\tpublic float convertOrigin(BenchEntityBones bone, BenchEntityCube cube, int index) {\n\t\tif (index == 1) {\n\t\t\treturn bone.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index);\n\t\t} else {\n\t\t\treturn cube.getOrigin().get(index) - bone.getPivot().get(index);\n\t\t}\n\t}\n\n\tpublic float convertOrigin(BenchEntityCube cube, int index) {\n\t\tassert cube.getPivot() != null;\n\t\tif (index == 1) {\n\t\t\treturn cube.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index);\n\t\t} else {\n\t\t\treturn cube.getOrigin().get(index) - cube.getPivot().get(index);\n\t\t}\n\t}\n\n\tpublic Optional<BenchEntityBones> getAnyDescendantWithName(String key) {\n\t\tOptional<Map.Entry<String, BenchEntityBones>> bones = this.getIndexBones().entrySet().stream().filter((benchBone) -> benchBone.getKey().equals(key)).findFirst();\n\t\tif (bones.isPresent()) {\n\t\t\treturn Optional.of(bones.get().getValue());\n\t\t} else {\n\t\t\treturn Optional.empty();\n\t\t}\n\t}\n\n\tprotected void animateWalk(AnimationData animationData, float p_268057_, float p_268347_, float p_268138_, float p_268165_) {\n\t\tlong time = (long) (p_268057_ * 50.0F * p_268138_);\n\t\tfloat scale = Math.min(p_268347_ * p_268165_, 1.0F);\n\t\tAnimationHelper.animate(this, animationData, time, scale, VEC_ANIMATION);\n\t}\n\n\tprotected void applyStatic(AnimationData animationData) {\n\t\tAnimationHelper.animate(this, animationData, 0L, 1.0F, VEC_ANIMATION);\n\t}\n\n\tprotected void animate(AnimationState animationState, AnimationData animationData, float p_233388_, float p_233389_) {\n\t\tanimationState.updateTime(p_233388_, p_233389_);\n\t\tanimationState.ifStarted(p_233392_ -> AnimationHelper.animate(this, animationData, p_233392_.getAccumulatedTime(), 1.0F, VEC_ANIMATION));\n\t}\n}" }, { "identifier": "Animation", "path": "src/main/java/useless/dragonfly/model/entity/animation/Animation.java", "snippet": "public class Animation {\n\tprivate final Map<String, AnimationData> animations;\n\n\tpublic Map<String, AnimationData> getAnimations() {\n\t\treturn animations;\n\t}\n\n\tpublic Animation(Map<String, AnimationData> animations) {\n\t\tthis.animations = animations;\n\t}\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public static final String MOD_ID = \"dragonfly\";" } ]
import net.minecraft.core.util.helper.MathHelper; import useless.dragonfly.helper.AnimationHelper; import useless.dragonfly.model.entity.BenchEntityModel; import useless.dragonfly.model.entity.animation.Animation; import static useless.dragonfly.DragonFly.MOD_ID;
6,972
package useless.dragonfly.debug.testentity.Zombie; public class ZombieModelTest extends BenchEntityModel { @Override public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { // If you need play some animation. you should reset with this this.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose()); super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); if (this.getIndexBones().containsKey("Head")) { this.getIndexBones().get("Head").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0); } if (this.getIndexBones().containsKey("bone")) { this.getIndexBones().get("bone").setRotationAngle(0, ticksExisted, 0); } if (this.getIndexBones().containsKey("RightArm")) { this.getIndexBones().get("RightArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0); } if (this.getIndexBones().containsKey("LeftArm")) { this.getIndexBones().get("LeftArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3)) * 2.0f * limbYaw * 0.5f, 0, 0); }
package useless.dragonfly.debug.testentity.Zombie; public class ZombieModelTest extends BenchEntityModel { @Override public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { // If you need play some animation. you should reset with this this.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose()); super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); if (this.getIndexBones().containsKey("Head")) { this.getIndexBones().get("Head").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0); } if (this.getIndexBones().containsKey("bone")) { this.getIndexBones().get("bone").setRotationAngle(0, ticksExisted, 0); } if (this.getIndexBones().containsKey("RightArm")) { this.getIndexBones().get("RightArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0); } if (this.getIndexBones().containsKey("LeftArm")) { this.getIndexBones().get("LeftArm").setRotationAngle(MathHelper.cos(limbSwing * (2f/3)) * 2.0f * limbYaw * 0.5f, 0, 0); }
Animation testAnimation = AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation");
0
2023-11-16 01:10:52+00:00
8k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/controller/ChartController.java
[ { "identifier": "R", "path": "src/main/java/top/sharehome/springbootinittemplate/common/base/R.java", "snippet": "@Data\n@NoArgsConstructor\npublic class R<T> {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 成功状态码\n */\n public static final int SUCCESS = ReturnCode.SUCCESS.getCode();\n\n /**\n * 成功响应值\n */\n public static final String SUCCESS_MSG = ReturnCode.SUCCESS.getMsg();\n\n /**\n * 失败状态码\n */\n public static final int FAIL = ReturnCode.FAIL.getCode();\n\n /**\n * 失败响应值\n */\n public static final String FAIL_MSG = ReturnCode.FAIL.getMsg();\n\n /**\n * 警告状态码\n */\n public static final int WARN = ReturnCode.WARN.getCode();\n\n /**\n * 警告响应值\n */\n public static final String WARN_MSG = ReturnCode.WARN.getMsg();\n\n /**\n * 消息状态码\n */\n private int code;\n\n /**\n * 消息内容\n */\n private String msg;\n\n /**\n * 数据对象\n */\n private T data;\n\n private static <T> R<T> restResult(T data, int code, String msg) {\n R<T> r = new R<>();\n r.setCode(code);\n r.setData(data);\n r.setMsg(msg);\n return r;\n }\n\n /**\n * 是否失败\n */\n public static <T> Boolean isError(R<T> ret) {\n return FAIL == ret.getCode();\n }\n\n /**\n * 是否成功\n */\n public static <T> Boolean isSuccess(R<T> ret) {\n return SUCCESS == ret.getCode();\n }\n\n // todo 成功响应方法\n public static <T> R<T> ok() {\n return restResult(null, SUCCESS, SUCCESS_MSG);\n }\n\n public static <T> R<T> ok(T data) {\n return restResult(data, SUCCESS, SUCCESS_MSG);\n }\n\n public static <T> R<T> ok(String msg) {\n return restResult(null, SUCCESS, msg);\n }\n\n public static <T> R<T> ok(String msg, T data) {\n return restResult(data, SUCCESS, msg);\n }\n\n // todo 失败响应方法\n public static <T> R<T> fail() {\n return restResult(null, FAIL, FAIL_MSG);\n }\n\n public static <T> R<T> fail(String msg) {\n return restResult(null, FAIL, msg);\n }\n\n public static <T> R<T> fail(T data) {\n return restResult(data, FAIL, FAIL_MSG);\n }\n\n public static <T> R<T> fail(String msg, T data) {\n return restResult(data, FAIL, msg);\n }\n\n public static <T> R<T> fail(int code, String msg) {\n return restResult(null, code, msg);\n }\n\n public static <T> R<T> fail(ReturnCode returnCode) {\n return restResult(null, returnCode.getCode(), returnCode.getMsg());\n }\n\n public static <T> R<T> fail(T data, ReturnCode returnCode) {\n return restResult(data, returnCode.getCode(), returnCode.getMsg());\n }\n\n // todo 警告响应方法\n public static <T> R<T> warn() {\n return restResult(null, WARN, WARN_MSG);\n }\n\n public static <T> R<T> warn(String msg) {\n return restResult(null, WARN, msg);\n }\n\n public static <T> R<T> warn(String msg, T data) {\n return restResult(data, WARN, msg);\n }\n\n}" }, { "identifier": "ReturnCode", "path": "src/main/java/top/sharehome/springbootinittemplate/common/base/ReturnCode.java", "snippet": "@Getter\npublic enum ReturnCode {\n\n /**\n * 操作成功 200\n */\n SUCCESS(HttpStatus.SUCCESS, \"操作成功\"),\n\n /**\n * 操作失败 500\n */\n FAIL(HttpStatus.ERROR, \"操作失败\"),\n\n /**\n * 系统警告 600\n */\n WARN(HttpStatus.WARN, \"系统警告\"),\n\n /**\n * 账户名称校验失败 11000\n */\n USERNAME_VALIDATION_FAILED(11000, \"账户名称校验失败\"),\n\n /**\n * 账户名称已经存在 11001\n */\n USERNAME_ALREADY_EXISTS(11001, \"账户名称已经存在\"),\n\n /**\n * 账户名称包含特殊字符 11002\n */\n PASSWORD_AND_SECONDARY_PASSWORD_NOT_SAME(11002, \"密码和二次密码不相同\"),\n\n /**\n * 密码校验失败 11003\n */\n PASSWORD_VERIFICATION_FAILED(11003, \"密码校验失败\"),\n\n /**\n * 用户基本信息校验失败 11004\n */\n USER_BASIC_INFORMATION_VERIFICATION_FAILED(11004, \"用户基本信息校验失败\"),\n\n /**\n * 用户账户不存在 11005\n */\n USER_ACCOUNT_DOES_NOT_EXIST(11005, \"用户账户不存在\"),\n\n /**\n * 用户账户被封禁 11006\n */\n USER_ACCOUNT_BANNED(11006, \"用户账户被封禁\"),\n\n /**\n * 用户账号或密码错误 11007\n */\n WRONG_USER_ACCOUNT_OR_PASSWORD(11007, \"用户账号或密码错误\"),\n\n /**\n * 用户登录已过期 11008\n */\n USER_LOGIN_HAS_EXPIRED(11008, \"用户登录已过期\"),\n\n /**\n * 用户操作异常 11009\n */\n ABNORMAL_USER_OPERATION(11009, \"用户操作异常\"),\n\n /**\n * 用户设备异常 11010\n */\n ABNORMAL_USER_EQUIPMENT(11010, \"用户设备异常\"),\n\n /**\n * 用户登录验证码为空 11011\n */\n CAPTCHA_IS_EMPTY(11011, \"验证码为空\"),\n\n /**\n * 用户登录验证码已过期 11012\n */\n CAPTCHA_HAS_EXPIRED(11012, \"验证码已过期\"),\n\n /**\n * 用户登录验证码无效 11013\n */\n CAPTCHA_IS_INVALID(11013, \"验证码无效\"),\n\n /**\n * 用户登录验证码无效 11014\n */\n CAPTCHA_IS_INCORRECT(11014, \"验证码错误\"),\n\n /**\n * 用户发出无效请求 11015\n */\n USER_SENT_INVALID_REQUEST(11015, \"用户发出无效请求\"),\n\n /**\n * 手机格式校验失败 12000\n */\n PHONE_FORMAT_VERIFICATION_FAILED(12000, \"手机格式校验失败\"),\n\n /**\n * 邮箱格式校验失败 12001\n */\n EMAIL_FORMAT_VERIFICATION_FAILED(12001, \"邮箱格式校验失败\"),\n\n /**\n * 访问未授权 13000\n */\n ACCESS_UNAUTHORIZED(13000, \"访问未授权\"),\n\n /**\n * 请求必填参数为空 13001\n */\n REQUEST_REQUIRED_PARAMETER_IS_EMPTY(13001, \"请求必填参数为空\"),\n\n /**\n * 参数格式不匹配 13002\n */\n PARAMETER_FORMAT_MISMATCH(13002, \"参数格式不匹配\"),\n\n /**\n * 用户请求次数太多 13003\n */\n TOO_MANY_REQUESTS(13003, \"用户请求次数太多\"),\n\n /**\n * 用户上传文件异常 14000\n */\n FILE_UPLOAD_EXCEPTION(14000, \"用户上传文件异常\"),\n\n /**\n * 用户没有上传文件 14001\n */\n USER_DO_NOT_UPLOAD_FILE(14001, \"用户没有上传文件\"),\n\n /**\n * 用户上传文件类型不匹配 14002\n */\n USER_UPLOADED_FILE_TYPE_MISMATCH(14002, \"用户上传文件类型不匹配\"),\n\n /**\n * 用户上传文件太大 14003\n */\n USER_UPLOADED_FILE_IS_TOO_LARGE(14003, \"用户上传文件太大\"),\n\n /**\n * 用户上传图片太大 14004\n */\n USER_UPLOADED_IMAGE_IS_TOO_LARGE(14004, \"用户上传图片太大\"),\n\n /**\n * 用户上传视频太大 14005\n */\n USER_UPLOADED_VIDEO_IS_TOO_LARGE(14005, \"用户上传视频太大\"),\n\n /**\n * 用户上传压缩文件太大 14006\n */\n USER_UPLOADED_ZIP_IS_TOO_LARGE(14006, \"用户上传压缩文件太大\"),\n\n /**\n * 用户文件地址异常 14007\n */\n USER_FILE_ADDRESS_IS_ABNORMAL(14007, \"用户文件地址异常\"),\n\n /**\n * 用户文件删除异常 14008\n */\n USER_FILE_DELETION_IS_ABNORMAL(14008, \"用户文件删除异常\"),\n\n /**\n * 系统文件地址异常 14009\n */\n SYSTEM_FILE_ADDRESS_IS_ABNORMAL(14007, \"系统文件地址异常\"),\n\n /**\n * 邮件发送异常 15000\n */\n EMAIL_WAS_SENT_ABNORMALLY(15000, \"邮件发送异常\"),\n\n /**\n * 数据库服务出错 20000\n */\n ERRORS_OCCURRED_IN_THE_DATABASE_SERVICE(20000, \"数据库服务出错\"),\n\n /**\n * 消息中间件服务出错 30000\n */\n MQ_SERVICE_ERROR(30000, \"消息中间件服务出错\"),\n\n /**\n * 内存数据库服务出错 30001\n */\n MAIN_MEMORY_DATABASE_SERVICE_ERROR(30001, \"内存数据库服务出错\"),\n\n /**\n * 搜索引擎服务出错 30002\n */\n SEARCH_ENGINE_SERVICE_ERROR(30002, \"搜索引擎服务出错\"),\n\n /**\n * 网关服务出错 30003\n */\n GATEWAY_SERVICE_ERROR(30003, \"网关服务出错\"),\n\n /**\n * 分布式锁服务出错 30004\n */\n LOCK_SERVICE_ERROR(30004, \"分布式锁服务出错\"),\n\n /**\n * 分布式锁设计出错 30005\n */\n LOCK_DESIGN_ERROR(30005, \"分布式锁设计出错\");\n\n final private int code;\n\n final private String msg;\n\n ReturnCode(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}" }, { "identifier": "CustomizeReturnException", "path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeReturnException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeReturnException extends RuntimeException {\n\n private ReturnCode returnCode;\n\n private String msg;\n\n public <T> CustomizeReturnException() {\n this.returnCode = ReturnCode.FAIL;\n this.msg = ReturnCode.FAIL.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode, String msg) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg() + \" ==> [\" + msg + \"]\";\n }\n\n @Override\n public String getMessage() {\n return this.msg;\n }\n\n}" }, { "identifier": "ChartGenDto", "path": "src/main/java/top/sharehome/springbootinittemplate/model/dto/chart/ChartGenDto.java", "snippet": "@Data\npublic class ChartGenDto implements Serializable {\n /**\n * 图表名称\n */\n @NotEmpty(message = \"图表名称不能为空\", groups = {PostGroup.class})\n private String name;\n\n /**\n * 分析目标\n */\n @NotEmpty(message = \"分析目标不能为空\", groups = {PostGroup.class})\n private String goal;\n\n /**\n * 图表类型\n */\n @NotEmpty(message = \"图表类型不能为空\", groups = {PostGroup.class})\n private String chartType;\n\n private static final long serialVersionUID = -8308107490110660374L;\n}" }, { "identifier": "ChartQueryDto", "path": "src/main/java/top/sharehome/springbootinittemplate/model/dto/chart/ChartQueryDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class ChartQueryDto implements Serializable {\n\n /**\n * id\n */\n @NotNull(message = \"查询目标ID为空\", groups = {GetGroup.class})\n private Long id;\n\n /**\n * 图表名称\n */\n private String name;\n\n /**\n * 分析目标\n */\n private String goal;\n\n /**\n * 图表类型\n */\n private String chartType;\n\n /**\n * 用户id\n */\n private Long userId;\n\n private static final long serialVersionUID = -8211825557632072540L;\n}" }, { "identifier": "Chart", "path": "src/main/java/top/sharehome/springbootinittemplate/model/entity/Chart.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(value = \"ai_bi.t_chart\")\npublic class Chart implements Serializable {\n /**\n * id\n */\n @TableId(value = \"chart_id\", type = IdType.ASSIGN_ID)\n private Long id;\n\n /**\n * 图表名称\n */\n @TableField(value = \"chart_name\")\n private String name;\n\n /**\n * 分析目标\n */\n @TableField(value = \"chart_goal\")\n private String goal;\n\n /**\n * 图标数据\n */\n @TableField(value = \"chart_chart_data\")\n private String chartData;\n\n /**\n * 图表类型\n */\n @TableField(value = \"chart_chart_type\")\n private String chartType;\n\n /**\n * 生成的图表数据\n */\n @TableField(value = \"chart_gen_chart\")\n private String genChart;\n\n /**\n * 生成的分析结论\n */\n @TableField(value = \"chart_gen_result\")\n private String genResult;\n\n /**\n * 用户id\n */\n @TableField(value = \"chart_user_id\")\n private Long userId;\n\n /**\n * 创建时间\n */\n @TableField(value = \"create_time\", fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n /**\n * 更新时间\n */\n @TableField(value = \"update_time\", fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime updateTime;\n\n /**\n * 逻辑删除(0表示未删除,1表示已删除)\n */\n @TableField(value = \"is_deleted\", fill = FieldFill.INSERT)\n @TableLogic\n private Integer isDeleted;\n\n private static final long serialVersionUID = 91865469458078099L;\n\n public static final String COL_CHART_ID = \"chart_id\";\n\n public static final String COL_CHART_NAME = \"chart_name\";\n\n public static final String COL_CHART_GOAL = \"chart_goal\";\n\n public static final String COL_CHART_CHART_DATA = \"chart_chart_data\";\n\n public static final String COL_CHART_CHART_TYPE = \"chart_chart_type\";\n\n public static final String COL_CHART_GEN_CHART = \"chart_gen_chart\";\n\n public static final String COL_CHART_GEN_RESULT = \"chart_gen_result\";\n\n public static final String COL_CHART_USER_ID = \"chart_user_id\";\n\n public static final String COL_CREATE_TIME = \"create_time\";\n\n public static final String COL_UPDATE_TIME = \"update_time\";\n\n public static final String COL_IS_DELETED = \"is_deleted\";\n}" }, { "identifier": "PageModel", "path": "src/main/java/top/sharehome/springbootinittemplate/model/entity/PageModel.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class PageModel implements Serializable {\n\n @NotNull(message = \"分页参数为空\")\n private Long page;\n\n @NotNull(message = \"分页参数为空\")\n @Size(min = 1, message = \"分页参数无效\")\n private Long pageSize;\n\n private static final long serialVersionUID = -1649075566134281161L;\n}" }, { "identifier": "ChartGenVo", "path": "src/main/java/top/sharehome/springbootinittemplate/model/vo/chart/ChartGenVo.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class ChartGenVo implements Serializable {\n private static final long serialVersionUID = -539879739760406303L;\n private String genChart;\n private String genResult;\n}" }, { "identifier": "ChartService", "path": "src/main/java/top/sharehome/springbootinittemplate/service/ChartService.java", "snippet": "public interface ChartService extends IService<Chart> {\n}" }, { "identifier": "ChatUtils", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/chat/ChatUtils.java", "snippet": "@Slf4j\npublic class ChatUtils {\n\n /**\n * 封装好的AI\n */\n private static final YuCongMingClient AI_CLIENT = SpringContextHolder.getBean(YuCongMingClient.class);\n\n public static String doChat(long modelId, String message) {\n DevChatRequest devChatRequest = new DevChatRequest();\n devChatRequest.setModelId(modelId);\n devChatRequest.setMessage(message);\n BaseResponse<DevChatResponse> response = AI_CLIENT.doChat(devChatRequest);\n if (response == null) {\n throw new CustomizeReturnException(ReturnCode.FAIL, \"AI 响应异常\");\n }\n return response.getData().getContent();\n }\n\n\n}" }, { "identifier": "ExcelUtils", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/excel/ExcelUtils.java", "snippet": "@Slf4j\npublic class ExcelUtils {\n public static String excelToCsv(MultipartFile multipartFile) {\n List<Map<Integer, String>> list = null;\n try {\n list = EasyExcel.read(multipartFile.getInputStream())\n .excelType(ExcelTypeEnum.XLSX)\n .sheet()\n .headRowNumber(0)\n .doReadSync();\n } catch (IOException e) {\n log.error(\"文件异常\");\n e.printStackTrace();\n }\n if (CollUtil.isEmpty(list)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n LinkedHashMap<Integer, String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);\n List<String> headerList = headerMap.values().stream().filter(Objects::nonNull).collect(Collectors.toList());\n sb.append(StringUtils.join(headerList, \",\")).append(\"\\n\");\n for (int i = 1; i < list.size(); i++) {\n LinkedHashMap<Integer, String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);\n List<String> dataList = dataMap.values().stream().filter(Objects::nonNull).collect(Collectors.toList());\n sb.append(StringUtils.join(dataList, \",\")).append(\"\\n\");\n }\n return sb.toString();\n }\n}" }, { "identifier": "LoginUtils", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/satoken/LoginUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class LoginUtils {\n\n private static final AuthService authService = SpringContextHolder.getBean(AuthService.class);\n\n /**\n * 用户登录\n *\n * @param loginUser 登录用户信息\n */\n public static void login(AuthLoginVo loginUser) {\n if (!StpUtil.isLogin()) {\n // 存入一份到缓存中\n SaHolder.getStorage()\n .set(Constants.LOGIN_USER_KEY, loginUser);\n StpUtil.login(loginUser.getId());\n StpUtil.getSession().set(Constants.LOGIN_USER_KEY, loginUser);\n } else {\n // 如果重复登录,就需要验证当前登录账号和将要登录账号是否相同,不相同则挤掉原账号,确保一个浏览器会话只存有一个账户信息\n if (ObjectUtils.notEqual(Long.parseLong((String) StpUtil.getLoginId()), loginUser.getId())) {\n StpUtil.logout();\n // 存入一份到缓存中\n SaHolder.getStorage()\n .set(Constants.LOGIN_USER_KEY, loginUser);\n StpUtil.login(loginUser.getId());\n StpUtil.getSession().set(Constants.LOGIN_USER_KEY, loginUser);\n }\n }\n }\n\n /**\n * 同步缓存中的用户登录信息\n */\n public static void syncLoginUser() {\n Long loginUserId = Long.valueOf((String) StpUtil.getLoginId());\n User userInDatabase = authService.getById(loginUserId);\n if (ObjectUtils.isEmpty(userInDatabase)) {\n StpUtil.logout(loginUserId);\n throw new CustomizeReturnException(ReturnCode.ACCESS_UNAUTHORIZED);\n }\n AuthLoginVo loginUser = new AuthLoginVo();\n BeanUtils.copyProperties(userInDatabase, loginUser);\n SaHolder.getStorage()\n .set(Constants.LOGIN_USER_KEY, loginUser);\n StpUtil.getSession().set(Constants.LOGIN_USER_KEY, loginUser);\n }\n\n /**\n * 从缓存中获取登录用户信息\n */\n public static AuthLoginVo getLoginUser() {\n AuthLoginVo loginUser = (AuthLoginVo) SaHolder.getStorage().get(Constants.LOGIN_USER_KEY);\n if (ObjectUtils.isNotEmpty(loginUser)) {\n return loginUser;\n }\n loginUser = (AuthLoginVo) StpUtil.getSession().get(Constants.LOGIN_USER_KEY);\n SaHolder.getStorage().set(Constants.LOGIN_USER_KEY, loginUser);\n return loginUser;\n }\n\n /**\n * 从缓存中获取登录用户ID\n */\n public static Long getLoginUserId() {\n return getLoginUser().getId();\n }\n\n /**\n * 从缓存中获取登录用户账户\n */\n public static String getLoginUserAccount() {\n return getLoginUser().getAccount();\n }\n\n /**\n * 登录用户账户角色是否为管理员\n */\n public static boolean isAdmin() {\n return Constants.USER_ROLE_ADMIN.equals(getLoginUser().getRole());\n }\n\n /**\n * 用户退出\n */\n public static void logout() {\n StpUtil.logout();\n }\n\n}" } ]
import cn.dev33.satoken.annotation.SaCheckLogin; import cn.hutool.core.io.FileUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import top.sharehome.springbootinittemplate.common.base.R; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.model.dto.chart.ChartGenDto; import top.sharehome.springbootinittemplate.model.dto.chart.ChartQueryDto; import top.sharehome.springbootinittemplate.model.entity.Chart; import top.sharehome.springbootinittemplate.model.entity.PageModel; import top.sharehome.springbootinittemplate.model.vo.chart.ChartGenVo; import top.sharehome.springbootinittemplate.service.ChartService; import top.sharehome.springbootinittemplate.utils.chat.ChatUtils; import top.sharehome.springbootinittemplate.utils.excel.ExcelUtils; import top.sharehome.springbootinittemplate.utils.satoken.LoginUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List;
5,980
package top.sharehome.springbootinittemplate.controller; /** * 图表接口 * * @author AntonyCheng */ @RestController @RequestMapping("/chart") @Slf4j @SaCheckLogin public class ChartController { @Resource private ChartService chartService; /** * 分页获取当前用户创建的资源列表 * todo 修改返回参数 * * @param chartQueryDto 分页查询Dto类 * @param pageModel 分页实体类 * @return */ @PostMapping("/user/list/page") public R<Page<Chart>> listMyChartByPage(@Validated @RequestBody PageModel pageModel, @Validated @RequestBody ChartQueryDto chartQueryDto) {
package top.sharehome.springbootinittemplate.controller; /** * 图表接口 * * @author AntonyCheng */ @RestController @RequestMapping("/chart") @Slf4j @SaCheckLogin public class ChartController { @Resource private ChartService chartService; /** * 分页获取当前用户创建的资源列表 * todo 修改返回参数 * * @param chartQueryDto 分页查询Dto类 * @param pageModel 分页实体类 * @return */ @PostMapping("/user/list/page") public R<Page<Chart>> listMyChartByPage(@Validated @RequestBody PageModel pageModel, @Validated @RequestBody ChartQueryDto chartQueryDto) {
chartQueryDto.setUserId(LoginUtils.getLoginUserId());
11
2023-11-12 07:49:59+00:00
8k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/VertexBatch.java
[ { "identifier": "AttribType", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/AttribType.java", "snippet": "public enum AttribType {\n /** GLSL {@code float} */\n FLOAT(1),\n /** GLSL {@code vec2} */\n VEC2(2),\n /** GLSL {@code vec3} */\n VEC3(3),\n /** GLSL {@code vec4} */\n VEC4(4);\n\n private final int elemCount;\n\n AttribType(int elemCount) {\n this.elemCount = elemCount;\n }\n\n /**\n * Gets the number of values within this type.\n *\n * @return element count\n */\n public int getElemCount() {\n return elemCount;\n }\n\n /**\n * Gets the size of this type in bytes.\n *\n * @return size in bytes\n */\n public int sizeOf() {\n return elemCount * SizeOf.FLOAT;\n }\n}" }, { "identifier": "MeshData", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/MeshData.java", "snippet": "public final class MeshData implements SafeCloseable {\n private static final int INITIAL_CAPACITY = 16;\n\n private final PrimitiveType primType;\n private final VertexLayout layout;\n private int layoutElemIdx;\n\n private ByteBuffer vertexBuf;\n private final List<Integer> indices;\n private int mark;\n private boolean finished;\n private int finalVertexCount;\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, AttribType... layout) {\n this(primType, new VertexLayout(layout));\n }\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, VertexLayout layout) {\n this.primType = primType;\n this.layout = layout;\n layoutElemIdx = 0;\n\n indices = new ArrayList<>();\n mark = 0;\n finished = false;\n\n vertexBuf = MemoryUtil.memAlloc(INITIAL_CAPACITY * layout.sizeOf());\n }\n\n private void ensureSpace(int spaceBytes) {\n if (vertexBuf.remaining() < spaceBytes) {\n int cap = vertexBuf.capacity();\n vertexBuf = MemoryUtil.memRealloc(vertexBuf, Math.max(cap + spaceBytes, cap * 2));\n }\n }\n\n private void prepare(AttribType type) {\n AttribType[] types = layout.getTypes();\n\n ensureSpace(type.sizeOf());\n AttribType layoutType = types[layoutElemIdx++];\n if (layoutType != type)\n throw new IllegalStateException(\"Incorrect attribute added for format (added \" + type + \", layout specifies \" + layoutType + \")\");\n if (layoutElemIdx >= types.length)\n layoutElemIdx = 0;\n }\n\n /**\n * Marks the current position. The mark position is added to\n * indices added after this is called.\n *\n * @return this\n */\n public MeshData mark() {\n mark = getVertexCount();\n return this;\n }\n\n /**\n * Adds a {@code float} value.\n *\n * @param f value to add\n * @return this\n */\n public MeshData putFloat(float f) {\n prepare(AttribType.FLOAT);\n vertexBuf.putFloat(f);\n return this;\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec2(Vector2f vec) {\n return putVec2(vec.x, vec.y);\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @return this\n */\n public MeshData putVec2(float x, float y) {\n prepare(AttribType.VEC2);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n return this;\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec3(Vector3f vec) {\n return putVec3(vec.x, vec.y, vec.z);\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @return this\n */\n public MeshData putVec3(float x, float y, float z) {\n prepare(AttribType.VEC3);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n return this;\n }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec4(Vector4f vec) { return putVec4(vec.x, vec.y, vec.z, vec.w); }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @param w w coordinate of the value\n * @return this\n */\n public MeshData putVec4(float x, float y, float z, float w) {\n prepare(AttribType.VEC4);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n vertexBuf.putFloat(w);\n return this;\n }\n\n /**\n * Adds an index to the index array. The index is added to the mark\n * position before adding it.\n *\n * @param i the index to add\n * @return this\n */\n public MeshData index(int i) {\n indices.add(mark + i);\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(int... indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(List<Integer> indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Appends another mesh data buffer to this. This will not modify the\n * source buffer.\n *\n * @param other mesh data to append\n * @return this\n */\n public MeshData append(MeshData other) {\n if (primType != other.primType)\n throw new IllegalArgumentException(\"Can only append data with same primitive type\");\n if (!layout.equals(other.layout))\n throw new IllegalArgumentException(\"Can only append data with same layout\");\n\n // Make sure our buffer is big enough\n ensureSpace(other.vertexBuf.position());\n\n mark();\n\n // Back up other buffer's bounds\n int posTmp = other.vertexBuf.position();\n int limitTmp = other.vertexBuf.limit();\n\n // Copy in the data\n other.vertexBuf.flip();\n vertexBuf.put(other.vertexBuf);\n\n // Restore backed up bounds\n other.vertexBuf.position(posTmp);\n other.vertexBuf.limit(limitTmp);\n\n // Copy indices with mark applied\n for (int i : other.indices) {\n indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Marks this data as finished, so no other data can be added.\n *\n * @return this\n */\n public MeshData finish() {\n if (finished) throw new IllegalStateException(\"Already finished\");\n finalVertexCount = getVertexCount();\n finished = true;\n vertexBuf.flip();\n return this;\n }\n\n /**\n * Gets the native data buffer. Do not free the returned buffer.\n *\n * @return vertex buffer\n */\n public ByteBuffer getVertexBuf() {\n if (!finished)\n finish();\n return vertexBuf;\n }\n\n /**\n * Gets the vertex layout this mesh data uses.\n *\n * @return layout\n */\n public VertexLayout getVertexLayout() {\n return layout;\n }\n\n /**\n * Gets the number of vertices in this data.\n *\n * @return vertex count\n */\n public int getVertexCount() {\n if (finished) return finalVertexCount;\n return vertexBuf.position() / layout.sizeOf();\n }\n\n /**\n * Gets the index array in this data.\n *\n * @return indices\n */\n public List<Integer> getIndices() {\n return indices;\n }\n\n /**\n * Gets the primitive type the vertices should be rendered as.\n *\n * @return primitive type\n */\n public PrimitiveType getPrimitiveType() {\n return primType;\n }\n\n /**\n * Gets the current mark position.\n *\n * @return mark\n */\n public int getMark() {\n return mark;\n }\n\n @Override\n public void close() {\n MemoryUtil.memFree(vertexBuf);\n }\n}" }, { "identifier": "PrimitiveType", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/PrimitiveType.java", "snippet": "public enum PrimitiveType {\n /** Each vertex is its own individual point. */\n POINTS,\n\n /** The points are connected with lines. */\n LINE_STRIP,\n\n /**\n * The points are connected with lines, and the last is connected to the\n * first.\n */\n LINE_LOOP,\n\n /** Each set of two vertices form the endpoints of a line. */\n LINES,\n\n /**\n * Each vertex forms a triangle with itself and the previous two vertices.\n */\n TRIANGLE_STRIP,\n\n /**\n * Each vertex forms a triangle with itself, the previous vertex, and the\n * first vertex.\n */\n TRIANGLE_FAN,\n\n /** Each set of three vertices form an individual triangle. */\n TRIANGLES\n}" }, { "identifier": "VertexLayout", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/VertexLayout.java", "snippet": "public final class VertexLayout {\n private final AttribType[] types;\n private final int sizeOf;\n\n /**\n * Creates a new layout of the specified attribute types.\n *\n * @param types vertex attribute types\n */\n public VertexLayout(AttribType... types) {\n this.types = types;\n\n int sz = 0;\n for (AttribType type : types)\n sz += type.sizeOf();\n sizeOf = sz;\n }\n\n /**\n * Gets the attribute types in this layout.\n *\n * @return types\n */\n public AttribType[] getTypes() {\n return types;\n }\n\n /**\n * Gets the total size of one vertex in bytes.\n *\n * @return size of vertex in bytes\n */\n public int sizeOf() {\n return sizeOf;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n VertexLayout that = (VertexLayout) o;\n return sizeOf == that.sizeOf &&\n Arrays.equals(types, that.types);\n }\n\n @Override\n public int hashCode() {\n int result = Objects.hash(sizeOf);\n result = 31 * result + Arrays.hashCode(types);\n return result;\n }\n}" }, { "identifier": "Texture2D", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Texture2D.java", "snippet": "public interface Texture2D extends Texture, Texture2DRegion {\n /**\n * Uploads a set of bitmap data to the GPU.\n *\n * @param data data to upload\n */\n void setData(BitmapRegion data);\n\n /**\n * Sets a section of the texture data on GPU, leaving the rest the same.\n *\n * @param data data to upload\n * @param x x coordinate to upload into\n * @param y y coordinate to upload into\n */\n void setSubData(BitmapRegion data, int x, int y);\n\n @Override\n default Texture2D getSourceTexture() {\n return this;\n }\n\n @Override\n default Vector2f getRegionTopLeftUV() {\n return new Vector2f(0, 0);\n }\n\n @Override\n default Vector2f getRegionBottomRightUV() {\n return new Vector2f(1, 1);\n }\n}" }, { "identifier": "Texture2DRegion", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Texture2DRegion.java", "snippet": "public interface Texture2DRegion {\n /**\n * Gets the texture this region is a part of.\n *\n * @return the source texture\n */\n Texture2D getSourceTexture();\n\n /**\n * Gets the top-left UV coordinates of the region in the source texture.\n *\n * @return top-left UV\n */\n Vector2f getRegionTopLeftUV();\n\n /**\n * Gets the bottom-right UV coordinates of the region in the source texture.\n *\n * @return bottom-right UV\n */\n Vector2f getRegionBottomRightUV();\n\n /**\n * Gets a sub-region of this texture. The positions specified here are\n * fractions from 0 to 1 of this region.\n *\n * @param leftX left x position fraction\n * @param topY top y position fraction\n * @param rightX right x position fraction\n * @param bottomY bottom y position fraction\n * @return the sub-region\n */\n default Texture2DRegion getSubRegion(float leftX, float topY, float rightX, float bottomY) {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(MathUtil.lerp(min.x, max.x, leftX), MathUtil.lerp(min.y, max.y, topY)),\n new Vector2f(MathUtil.lerp(min.x, max.x, rightX), MathUtil.lerp(min.y, max.y, bottomY))\n );\n }\n\n /**\n * Gets a view of the region reflected over the X axis\n * @return flipped region\n */\n default Texture2DRegion getFlippedX() {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(min.x, max.y),\n new Vector2f(max.x, min.y)\n );\n }\n\n /**\n * Gets a view of the region reflected over the Y axis\n * @return flipped region\n */\n default Texture2DRegion getFlippedY() {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(max.x, min.y),\n new Vector2f(min.x, max.y)\n );\n }\n}" } ]
import com.github.rmheuer.azalea.render.mesh.AttribType; import com.github.rmheuer.azalea.render.mesh.MeshData; import com.github.rmheuer.azalea.render.mesh.PrimitiveType; import com.github.rmheuer.azalea.render.mesh.VertexLayout; import com.github.rmheuer.azalea.render.texture.Texture2D; import com.github.rmheuer.azalea.render.texture.Texture2DRegion; import java.util.List;
4,195
package com.github.rmheuer.azalea.render2d; /** * A batch of vertices to draw. */ final class VertexBatch { /** * The layout of the generated vertex data. */ public static final VertexLayout LAYOUT = new VertexLayout( AttribType.VEC3, // Position AttribType.VEC2, // Texture coord AttribType.VEC4, // Color AttribType.FLOAT // Texture slot ); private final Texture2D[] textures;
package com.github.rmheuer.azalea.render2d; /** * A batch of vertices to draw. */ final class VertexBatch { /** * The layout of the generated vertex data. */ public static final VertexLayout LAYOUT = new VertexLayout( AttribType.VEC3, // Position AttribType.VEC2, // Texture coord AttribType.VEC4, // Color AttribType.FLOAT // Texture slot ); private final Texture2D[] textures;
private final MeshData data;
1
2023-11-16 04:46:53+00:00
8k
Shushandr/offroad
src/net/osmand/binary/BinaryMapDataObject.java
[ { "identifier": "MapIndex", "path": "src/net/osmand/binary/BinaryMapIndexReader.java", "snippet": "public static class MapIndex extends BinaryIndexPart {\n\tList<MapRoot> roots = new ArrayList<MapRoot>();\n\t\t\n\tMap<String, Map<String, Integer> > encodingRules = new HashMap<String, Map<String, Integer> >();\n\tpublic TIntObjectMap<TagValuePair> decodingRules = new TIntObjectHashMap<TagValuePair>();\n\tpublic int nameEncodingType = 0;\n\tpublic int nameEnEncodingType = -1;\n\tpublic int refEncodingType = -1;\n\tpublic int coastlineEncodingType = -1;\n\tpublic int coastlineBrokenEncodingType = -1;\n\tpublic int landEncodingType = -1;\n\tpublic int onewayAttribute = -1;\n\tpublic int onewayReverseAttribute = -1;\n\tpublic TIntHashSet positiveLayers = new TIntHashSet(2);\n\tpublic TIntHashSet negativeLayers = new TIntHashSet(2);\n\t\t\n\tpublic Integer getRule(String t, String v){\n\t\tMap<String, Integer> m = encodingRules.get(t);\n\t\tif(m != null){\n\t\t\treturn m.get(v);\n\t\t}\n\t\treturn null;\n\t}\n\t\t\n\tpublic List<MapRoot> getRoots() {\n\t\treturn roots;\n\t}\n\t\t\n\tpublic TagValuePair decodeType(int type){\n\t\treturn decodingRules.get(type);\n\t}\n\n\tpublic void finishInitializingTags() {\n\t\tint free = decodingRules.size() * 2 + 1;\n\t\tcoastlineBrokenEncodingType = free++;\n\t\tinitMapEncodingRule(0, coastlineBrokenEncodingType, \"natural\", \"coastline_broken\");\n\t\tif(landEncodingType == -1){\n\t\t\tlandEncodingType = free++;\n\t\t\tinitMapEncodingRule(0, landEncodingType, \"natural\", \"land\");\n\t\t}\n\t}\n\t\t\n\tpublic boolean isRegisteredRule(int id) {\n\t\treturn decodingRules.containsKey(id);\n\t}\n\t\t\n\tpublic void initMapEncodingRule(int type, int id, String tag, String val) {\n\t\tif(!encodingRules.containsKey(tag)){\n\t\t\tencodingRules.put(tag, new HashMap<String, Integer>());\n\t\t}\n\t\tencodingRules.get(tag).put(val, id);\n\t\tif(!decodingRules.containsKey(id)){\n\t\t\tdecodingRules.put(id, new TagValuePair(tag, val, type));\n\t\t}\n\t\t\t\n\t\tif(\"name\".equals(tag)){\n\t\t\tnameEncodingType = id;\n\t\t} else if(\"natural\".equals(tag) && \"coastline\".equals(val)){\n\t\t\tcoastlineEncodingType = id;\n\t\t} else if(\"natural\".equals(tag) && \"land\".equals(val)){\n\t\t\tlandEncodingType = id;\n\t\t} else if(\"oneway\".equals(tag) && \"yes\".equals(val)){\n\t\t\tonewayAttribute = id;\n\t\t} else if(\"oneway\".equals(tag) && \"-1\".equals(val)){\n\t\t\tonewayReverseAttribute = id;\n\t\t} else if(\"ref\".equals(tag)){\n\t\t\trefEncodingType = id;\n\t\t} else if(\"name:en\".equals(tag)){\n\t\t\tnameEnEncodingType = id;\n\t\t} else if(\"tunnel\".equals(tag)){\n\t\t\tnegativeLayers.add(id);\n\t\t} else if(\"bridge\".equals(tag)){\n\t\t\tpositiveLayers.add(id);\n\t\t} else if(\"layer\".equals(tag)){\n\t\t\tif(val != null && !val.equals(\"0\") && val.length() > 0) {\n\t\t\t\tif(val.startsWith(\"-\")) {\n\t\t\t\t\tnegativeLayers.add(id);\n\t\t\t\t} else {\n\t\t\t\t\tpositiveLayers.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isBaseMap(){\n\t\treturn name != null && name.toLowerCase().contains(BASEMAP_NAME);\n\t}\n}" }, { "identifier": "RenderingRulesStorage", "path": "src/net/osmand/render/RenderingRulesStorage.java", "snippet": "public class RenderingRulesStorage {\n\n\tprivate final static Log log = PlatformUtil.getLog(RenderingRulesStorage.class);\n\tstatic boolean STORE_ATTTRIBUTES = false;\n\t\n\t// keep sync !\n\t// keep sync ! not change values\n\tpublic final static int MULTY_POLYGON_TYPE = 0;\n\tpublic final static int POINT_RULES = 1;\n\tpublic final static int LINE_RULES = 2;\n\tpublic final static int POLYGON_RULES = 3;\n\tpublic final static int TEXT_RULES = 4;\n\tpublic final static int ORDER_RULES = 5;\n\tpublic final static int LENGTH_RULES = 6;\n\t\n\tprivate final static int SHIFT_TAG_VAL = 16;\n\t\n\t// C++\n\tList<String> dictionary = new ArrayList<String>();\n\tMap<String, Integer> dictionaryMap = new LinkedHashMap<String, Integer>();\n\t\n\tpublic RenderingRuleStorageProperties PROPS = new RenderingRuleStorageProperties();\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic TIntObjectHashMap<RenderingRule>[] tagValueGlobalRules = new TIntObjectHashMap[LENGTH_RULES];\n\t\n\tprotected Map<String, RenderingRule> renderingAttributes = new LinkedHashMap<String, RenderingRule>();\n\tprotected Map<String, String> renderingConstants = new LinkedHashMap<String, String>();\n\t\n\tprotected String renderingName;\n\tprotected String internalRenderingName;\n\t\n\t\n\tpublic static interface RenderingRulesStorageResolver {\n\t\t\n\t\tRenderingRulesStorage resolve(String name, RenderingRulesStorageResolver ref) throws XmlPullParserException, IOException;\n\t}\n\t\n\tpublic RenderingRulesStorage(String name, Map<String, String> renderingConstants){\n\t\tgetDictionaryValue(\"\");\n\t\tthis.renderingName = name;\n\t\tif(renderingConstants != null) {\n\t\t\tthis.renderingConstants.putAll(renderingConstants);\n\t\t}\n\t}\n\t\n\tpublic int getDictionaryValue(String val) {\n\t\tif(dictionaryMap.containsKey(val)){\n\t\t\treturn dictionaryMap.get(val);\n\t\t}\n\t\tint nextInd = dictionaryMap.size();\n\t\tdictionaryMap.put(val, nextInd);\n\t\tdictionary.add(val);\n\t\treturn nextInd;\n\n\t}\n\t\n\tpublic String getStringValue(int i){\n\t\treturn dictionary.get(i);\n\t}\n\t\n\t\n\tpublic String getName() {\n\t\treturn renderingName;\n\t}\n\t\n\tpublic String getInternalRenderingName() {\n\t\treturn internalRenderingName;\n\t}\n\t\n\t\n\tpublic void parseRulesFromXmlInputStream(InputStream is, RenderingRulesStorageResolver resolver) throws XmlPullParserException,\n\t\t\tIOException {\n\t\tXmlPullParser parser = PlatformUtil.newXMLPullParser();\n\t\tRenderingRulesHandler handler = new RenderingRulesHandler(parser, resolver);\n\t\thandler.parse(is);\n\t\tRenderingRulesStorage depends = handler.getDependsStorage();\n\t\tif (depends != null) {\n\t\t\t// merge results\n\t\t\t// dictionary and props are already merged\n\t\t\tIterator<Entry<String, RenderingRule>> it = depends.renderingAttributes.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tEntry<String, RenderingRule> e = it.next();\n\t\t\t\tif (renderingAttributes.containsKey(e.getKey())) {\n\t\t\t\t\tRenderingRule root = renderingAttributes.get(e.getKey());\n\t\t\t\t\tList<RenderingRule> list = e.getValue().getIfElseChildren();\n\t\t\t\t\tfor (RenderingRule every : list) {\n\t\t\t\t\t\troot.addIfElseChildren(every);\n\t\t\t\t\t}\n\t\t\t\t\te.getValue().addToBeginIfElseChildren(root);\n\t\t\t\t} else {\n\t\t\t\t\trenderingAttributes.put(e.getKey(), e.getValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < LENGTH_RULES; i++) {\n\t\t\t\tif (depends.tagValueGlobalRules[i] == null || depends.tagValueGlobalRules[i].isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tagValueGlobalRules[i] != null) {\n\t\t\t\t\tint[] keys = depends.tagValueGlobalRules[i].keys();\n\t\t\t\t\tfor (int j = 0; j < keys.length; j++) {\n\t\t\t\t\t\tRenderingRule rule = tagValueGlobalRules[i].get(keys[j]);\n\t\t\t\t\t\tRenderingRule dependsRule = depends.tagValueGlobalRules[i].get(keys[j]);\n\t\t\t\t\t\tif (dependsRule != null) {\n\t\t\t\t\t\t\tif (rule != null) {\n\t\t\t\t\t\t\t\tRenderingRule toInsert = createTagValueRootWrapperRule(keys[j], rule);\n\t\t\t\t\t\t\t\ttoInsert.addIfElseChildren(dependsRule);\n\t\t\t\t\t\t\t\ttagValueGlobalRules[i].put(keys[j], toInsert);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttagValueGlobalRules[i].put(keys[j], dependsRule);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttagValueGlobalRules[i] = depends.tagValueGlobalRules[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic static String colorToString(int color) {\n\t\tif ((0xFF000000 & color) == 0xFF000000) {\n\t\t\treturn \"#\" + Integer.toHexString(color & 0x00FFFFFF); //$NON-NLS-1$\n\t\t} else {\n\t\t\treturn \"#\" + Integer.toHexString(color); //$NON-NLS-1$\n\t\t}\n\t}\n\t\n\tprivate void registerGlobalRule(RenderingRule rr, int state, String tagS, String valueS) throws XmlPullParserException {\n\t\tif(tagS == null || valueS == null){\n\t\t\tthrow new XmlPullParserException(\"Attribute tag should be specified for root filter \" + rr.toString());\n\t\t}\n\t\tint tag = getDictionaryValue(tagS);\n\t\tint value = getDictionaryValue(valueS);\n\t\tint key = (tag << SHIFT_TAG_VAL) + value;\n\t\tRenderingRule insert = tagValueGlobalRules[state].get(key);\n\t\tif (insert != null) {\n\t\t\t// all root rules should have at least tag/value\n\t\t\tinsert = createTagValueRootWrapperRule(key, insert);\n\t\t\tinsert.addIfElseChildren(rr);\n\t\t} else {\n\t\t\tinsert = rr;\n\t\t}\n\t\ttagValueGlobalRules[state].put(key, insert);\t\t\t\n\t}\n\t\n\n\tprivate RenderingRule createTagValueRootWrapperRule(int tagValueKey, RenderingRule previous) {\n\t\tif (previous.getProperties().length > 0) {\n\t\t\tMap<String, String> m = new HashMap<String, String>();\n\t\t\tRenderingRule toInsert = new RenderingRule(m, true, RenderingRulesStorage.this);\n\t\t\ttoInsert.addIfElseChildren(previous);\n\t\t\treturn toInsert;\n\t\t} else {\n\t\t\treturn previous;\n\t\t}\n\t}\n\t\n\tprivate class RenderingRulesHandler {\n\t\tprivate final XmlPullParser parser;\n\t\tprivate int state;\n\n\t\tStack<RenderingRule> stack = new Stack<RenderingRule>();\n\t\t\n\t\tMap<String, String> attrsMap = new LinkedHashMap<String, String>();\n\t\tprivate final RenderingRulesStorageResolver resolver;\n\t\tprivate RenderingRulesStorage dependsStorage;\n\t\t\n\t\t\n\t\t\n\t\tpublic RenderingRulesHandler(XmlPullParser parser, RenderingRulesStorageResolver resolver){\n\t\t\tthis.parser = parser;\n\t\t\tthis.resolver = resolver;\n\t\t}\n\t\t\n\t\tpublic void parse(InputStream is) throws XmlPullParserException, IOException {\n\t\t\tparser.setInput(is, \"UTF-8\");\n\t\t\tint tok;\n\t\t\twhile ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {\n\t\t\t\tif (tok == XmlPullParser.START_TAG) {\n\t\t\t\t\tstartElement(parser.getName());\n\t\t\t\t} else if (tok == XmlPullParser.END_TAG) {\n\t\t\t\t\tendElement(parser.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic RenderingRulesStorage getDependsStorage() {\n\t\t\treturn dependsStorage;\n\t\t}\n\t\t\n\t\tprivate boolean isTopCase() {\n\t\t\tfor(int i = 0; i < stack.size(); i++) {\n\t\t\t\tif(!stack.get(i).isGroup()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tpublic void startElement(String name) throws XmlPullParserException, IOException {\n\t\t\tboolean stateChanged = false;\n\t\t\tfinal boolean isCase = isCase(name);\n\t\t\tfinal boolean isSwitch = isSwitch(name);\n\t\t\tif(isCase || isSwitch){ //$NON-NLS-1$\n\t\t\t\tattrsMap.clear();\n\t\t\t\tboolean top = stack.size() == 0 || isTopCase();\n\t\t\t\tparseAttributes(attrsMap);\n\t\t\t\tRenderingRule renderingRule = new RenderingRule(attrsMap, isSwitch, RenderingRulesStorage.this);\n\t\t\t\tif(top || STORE_ATTTRIBUTES){\n\t\t\t\t\trenderingRule.storeAttributes(attrsMap);\n\t\t\t\t}\n\t\t\t\tif (stack.size() > 0 && stack.peek() instanceof RenderingRule) {\n\t\t\t\t\tRenderingRule parent = ((RenderingRule) stack.peek());\n\t\t\t\t\tparent.addIfElseChildren(renderingRule);\n\t\t\t\t}\n\t\t\t\tstack.push(renderingRule);\n\t\t\t} else if(isApply(name)){ //$NON-NLS-1$\n\t\t\t\tattrsMap.clear();\n\t\t\t\tparseAttributes(attrsMap);\n\t\t\t\tRenderingRule renderingRule = new RenderingRule(attrsMap, false, RenderingRulesStorage.this);\n\t\t\t\tif(STORE_ATTTRIBUTES) {\n\t\t\t\t\trenderingRule.storeAttributes(attrsMap);\n\t\t\t\t}\n\t\t\t\tif (stack.size() > 0 && stack.peek() instanceof RenderingRule) {\n\t\t\t\t\t((RenderingRule) stack.peek()).addIfChildren(renderingRule);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new XmlPullParserException(\"Apply (groupFilter) without parent\");\n\t\t\t\t}\n\t\t\t\tstack.push(renderingRule);\n\t\t\t} else if(\"order\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstate = ORDER_RULES;\n\t\t\t\tstateChanged = true;\n\t\t\t} else if(\"text\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstate = TEXT_RULES;\n\t\t\t\tstateChanged = true;\n\t\t\t} else if(\"point\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstate = POINT_RULES;\n\t\t\t\tstateChanged = true;\n\t\t\t} else if(\"line\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstate = LINE_RULES;\n\t\t\t\tstateChanged = true;\n\t\t\t} else if(\"polygon\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstate = POLYGON_RULES;\n\t\t\t\tstateChanged = true;\n\t\t\t} else if(\"renderingAttribute\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tString attr = parser.getAttributeValue(\"\", \"name\");\n\t\t\t\tRenderingRule root = new RenderingRule(new HashMap<String, String>(), false, RenderingRulesStorage.this);\n\t\t\t\trenderingAttributes.put(attr, root);\n\t\t\t\tstack.push(root);\n\t\t\t} else if(\"renderingProperty\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tString attr = parser.getAttributeValue(\"\", \"attr\");\n\t\t\t\tRenderingRuleProperty prop;\n\t\t\t\tString type = parser.getAttributeValue(\"\", \"type\");\n\t\t\t\tif(\"boolean\".equalsIgnoreCase(type)){\n\t\t\t\t\tprop = RenderingRuleProperty.createInputBooleanProperty(attr);\n\t\t\t\t} else if(\"string\".equalsIgnoreCase(type)){\n\t\t\t\t\tprop = RenderingRuleProperty.createInputStringProperty(attr);\n\t\t\t\t} else {\n\t\t\t\t\tprop = RenderingRuleProperty.createInputIntProperty(attr);\n\t\t\t\t}\n\t\t\t\tprop.setDescription(parser.getAttributeValue(\"\", \"description\"));\n\t\t\t\tprop.setDefaultValueDescription(parser.getAttributeValue(\"\", \"defaultValueDescription\"));\n\t\t\t\tprop.setCategory(parser.getAttributeValue(\"\", \"category\"));\n\t\t\t\tprop.setName(parser.getAttributeValue(\"\", \"name\"));\n\t\t\t\tif(parser.getAttributeValue(\"\", \"possibleValues\") != null){\n\t\t\t\t\tprop.setPossibleValues(parser.getAttributeValue(\"\", \"possibleValues\").split(\",\"));\n\t\t\t\t}\n\t\t\t\tPROPS.registerRule(prop);\n\t\t\t} else if(\"renderingConstant\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tif(!renderingConstants.containsKey(parser.getAttributeValue(\"\", \"name\"))){\n\t\t\t\t\trenderingConstants.put(parser.getAttributeValue(\"\", \"name\"), parser.getAttributeValue(\"\", \"value\"));\n\t\t\t\t}\n\t\t\t} else if(\"renderingStyle\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tString depends = parser.getAttributeValue(\"\", \"depends\");\n\t\t\t\tif(depends != null && depends.length()> 0){\n\t\t\t\t\tthis.dependsStorage = resolver.resolve(depends, resolver);\n\t\t\t\t}\n\t\t\t\tif(dependsStorage != null){\n\t\t\t\t\t// copy dictionary\n\t\t\t\t\tdictionary = new ArrayList<String>(dependsStorage.dictionary);\n\t\t\t\t\tdictionaryMap = new LinkedHashMap<String, Integer>(dependsStorage.dictionaryMap);\n\t\t\t\t\tPROPS = new RenderingRuleStorageProperties(dependsStorage.PROPS);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tinternalRenderingName = parser.getAttributeValue(\"\", \"name\");\n\t\t\t\t\n\t\t\t} else if(\"renderer\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tthrow new XmlPullParserException(\"Rendering style is deprecated and no longer supported.\");\n\t\t\t} else {\n\t\t\t\tlog.warn(\"Unknown tag : \" + name); //$NON-NLS-1$\n\t\t\t}\n\t\t\t\n\t\t\tif(stateChanged){\n\t\t\t\ttagValueGlobalRules[state] = new TIntObjectHashMap<RenderingRule>();\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tprotected boolean isCase(String name) {\n\t\t\treturn \"filter\".equals(name) || \"case\".equals(name);\n\t\t}\n\n\t\tprotected boolean isApply(String name) {\n\t\t\treturn \"groupFilter\".equals(name) || \"apply\".equals(name) || \"apply_if\".equals(name);\n\t\t}\n\n\t\tprotected boolean isSwitch(String name) {\n\t\t\treturn \"group\".equals(name) || \"switch\".equals(name);\n\t\t}\n\t\t\n\t\tprivate Map<String, String> parseAttributes(Map<String, String> m) {\n\t\t\tfor (int i = 0; i < parser.getAttributeCount(); i++) {\n\t\t\t\tString name = parser.getAttributeName(i);\n\t\t\t\tString vl = parser.getAttributeValue(i);\n\t\t\t\tif (vl != null && vl.startsWith(\"$\")) {\n\t\t\t\t\tString cv = vl.substring(1);\n\t\t\t\t\tif (!renderingConstants.containsKey(cv) &&\n\t\t\t\t\t\t\t!renderingAttributes.containsKey(cv)) {\n\t\t\t\t\t\tthrow new IllegalStateException(\"Rendering constant or attribute '\" + cv + \"' was not specified.\");\n\t\t\t\t\t}\n\t\t\t\t\tif(renderingConstants.containsKey(cv)){\n\t\t\t\t\t\tvl = renderingConstants.get(cv);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm.put(name, vl);\n\t\t\t}\n\t\t\treturn m;\n\t\t}\n\n\n\t\tpublic void endElement(String name) throws XmlPullParserException {\n\t\t\tif (isCase(name) || isSwitch(name)) { \n\t\t\t\tRenderingRule renderingRule = (RenderingRule) stack.pop();\n\t\t\t\tif(stack.size() == 0) {\n\t\t\t\t\tregisterTopLevel(renderingRule, null, Collections.emptyMap());\n\t\t\t\t}\n\t\t\t} else if(isApply(name)){ \n\t\t\t\tstack.pop();\n\t\t\t} else if(\"renderingAttribute\".equals(name)){ //$NON-NLS-1$\n\t\t\t\tstack.pop();\n\t\t\t}\n\t\t}\n\n\t\tprotected void registerTopLevel(RenderingRule renderingRule, List<RenderingRule> applyRules, Map<String, String> attrs) throws XmlPullParserException {\n\t\t\tif(renderingRule.isGroup() && (renderingRule.getIntPropertyValue(RenderingRuleStorageProperties.TAG) == -1 ||\n\t\t\t\t\trenderingRule.getIntPropertyValue(RenderingRuleStorageProperties.VALUE) == -1)){\n\t\t\t\tList<RenderingRule> caseChildren = renderingRule.getIfElseChildren();\n\t\t\t\tfor(RenderingRule ch : caseChildren) {\n\t\t\t\t\tList<RenderingRule> apply = applyRules;\n\t\t\t\t\tif(!renderingRule.getIfChildren().isEmpty()) {\n\t\t\t\t\t\tapply = new ArrayList<RenderingRule>();\n\t\t\t\t\t\tapply.addAll(renderingRule.getIfChildren());\n\t\t\t\t\t\tif(applyRules != null) {\n\t\t\t\t\t\t\tapply.addAll(applyRules);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tMap<String, String> cattrs = new HashMap<String, String>(attrs);\n\t\t\t\t\tcattrs.putAll(renderingRule.getAttributes());\n\t\t\t\t\tregisterTopLevel(ch, apply, cattrs);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tString tg = null;\n\t\t\t\tString vl = null;\n\t\t\t\tHashMap<String, String> ns = new HashMap<String, String>(attrs);\n\t\t\t\tns.putAll(renderingRule.getAttributes());\n\t\t\t\ttg = ns.remove(\"tag\");\n\t\t\t\tvl = ns.remove(\"value\");\n\t\t\t\t// reset rendering rule attributes\n\t\t\t\trenderingRule.init(ns);\n\t\t\t\tif(STORE_ATTTRIBUTES) {\n\t\t\t\t\trenderingRule.storeAttributes(ns);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tregisterGlobalRule(renderingRule, state, tg, vl);\n\t\t\t\tif (applyRules != null) {\n\t\t\t\t\tfor (RenderingRule apply : applyRules) {\n\t\t\t\t\t\trenderingRule.addIfChildren(apply);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tpublic int getTagValueKey(String tag, String value){\n\t\tint itag = getDictionaryValue(tag);\n\t\tint ivalue = getDictionaryValue(value);\n\t\treturn (itag << SHIFT_TAG_VAL) | ivalue; \n\t}\n\t\n\tpublic String getValueString(int tagValueKey){\n\t\treturn getStringValue(tagValueKey & ((1 << SHIFT_TAG_VAL) - 1)); \n\t}\n\t\n\tpublic String getTagString(int tagValueKey){\n\t\treturn getStringValue(tagValueKey >> SHIFT_TAG_VAL); \n\t}\n\t\n\tprotected RenderingRule getRule(int state, int itag, int ivalue){\n\t\tif(tagValueGlobalRules[state] != null){\n\t\t\treturn tagValueGlobalRules[state].get((itag << SHIFT_TAG_VAL) | ivalue);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected RenderingRule getRenderingAttributeRule(String attribute){\n\t\treturn renderingAttributes.get(attribute);\n\t}\n\t\n\tpublic String[] getRenderingAttributeNames() {\n\t\treturn renderingAttributes.keySet().toArray(new String[renderingAttributes.size()]);\n\t}\n\tpublic RenderingRule[] getRenderingAttributeValues() {\n\t\treturn renderingAttributes.values().toArray(new RenderingRule[renderingAttributes.size()]);\n\t}\n\t\n\tpublic RenderingRule[] getRules(int state){\n\t\tif(state >= tagValueGlobalRules.length || tagValueGlobalRules[state] == null) {\n\t\t\treturn new RenderingRule[0];\n\t\t}\n\t\treturn tagValueGlobalRules[state].values(new RenderingRule[tagValueGlobalRules[state].size()]);\n\t}\n\t\n\tpublic int getRuleTagValueKey(int state, int ind){\n\t\treturn tagValueGlobalRules[state].keys()[ind];\n\t}\n\t\n\t\n\tpublic void printDebug(int state, PrintStream out){\n\t\tfor(int key : tagValueGlobalRules[state].keys()) {\n\t\t\tRenderingRule rr = tagValueGlobalRules[state].get(key);\n\t\t\tout.print(\"\\n\\n\"+getTagString(key) + \" : \" + getValueString(key) + \"\\n \");\n\t\t\tprintRenderingRule(\" \", rr, out);\n\t\t}\n\t}\n\t\n\tprivate static void printRenderingRule(String indent, RenderingRule rr, PrintStream out){\n\t\tout.print(rr.toString(indent, new StringBuilder()).toString());\n\t}\n\t\n\t\n\tpublic static void main(String[] args) throws XmlPullParserException, IOException {\n\t\tSTORE_ATTTRIBUTES = true;\n//\t\tInputStream is = RenderingRulesStorage.class.getResourceAsStream(\"default.render.xml\");\n\t\tfinal String loc = \"/Users/victorshcherb/osmand/repos/resources/rendering_styles/\";\n\t\tString defaultFile = loc + \"UniRS.render.xml\";\n\t\tif(args.length > 0) {\n\t\t\tdefaultFile = args[0];\n\t\t}\n\t\tfinal Map<String, String> renderingConstants = new LinkedHashMap<String, String>();\n\t\tInputStream is = new FileInputStream(loc + \"default.render.xml\");\n\t\ttry {\n\t\t\tXmlPullParser parser = PlatformUtil.newXMLPullParser();\n\t\t\tparser.setInput(is, \"UTF-8\");\n\t\t\tint tok;\n\t\t\twhile ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {\n\t\t\t\tif (tok == XmlPullParser.START_TAG) {\n\t\t\t\t\tString tagName = parser.getName();\n\t\t\t\t\tif (tagName.equals(\"renderingConstant\")) {\n\t\t\t\t\t\tif (!renderingConstants.containsKey(parser.getAttributeValue(\"\", \"name\"))) {\n\t\t\t\t\t\t\trenderingConstants.put(parser.getAttributeValue(\"\", \"name\"), \n\t\t\t\t\t\t\t\t\tparser.getAttributeValue(\"\", \"value\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tis.close();\n\t\t}\n\t\tRenderingRulesStorage storage = new RenderingRulesStorage(\"default\", renderingConstants);\n\t\tfinal RenderingRulesStorageResolver resolver = new RenderingRulesStorageResolver() {\n\t\t\t@Override\n\t\t\tpublic RenderingRulesStorage resolve(String name, RenderingRulesStorageResolver ref) throws XmlPullParserException, IOException {\n\t\t\t\tRenderingRulesStorage depends = new RenderingRulesStorage(name, renderingConstants);\n//\t\t\t\tdepends.parseRulesFromXmlInputStream(RenderingRulesStorage.class.getResourceAsStream(name + \".render.xml\"), ref);\n\t\t\t\tdepends.parseRulesFromXmlInputStream(new FileInputStream(loc + name + \".render.xml\"), ref);\n\t\t\t\treturn depends;\n\t\t\t}\n\t\t};\n\t\tis = new FileInputStream(defaultFile);\n\t\tstorage.parseRulesFromXmlInputStream(is, resolver);\n\t\t\n//\t\tstorage = new RenderingRulesStorage(\"\", null);\n//\t\tnew DefaultRenderingRulesStorage().createStyle(storage);\n\t\tfor (RenderingRuleProperty p : storage.PROPS.getCustomRules()) {\n\t\t\tSystem.out.println(p.getCategory() + \" \" + p.getName() + \" \" + p.getAttrName());\n\t\t}\n//\t\tprintAllRules(storage);\n//\t\ttestSearch(storage);\n\t\t\n\t}\n\t\n\t\n\t\n\tprotected static void testSearch(RenderingRulesStorage storage) {\n\t\t//\t\tlong tm = System.nanoTime();\n\t\t//\t\tint count = 100000;\n\t\t//\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\t\tRenderingRuleSearchRequest searchRequest = new RenderingRuleSearchRequest(storage);\n\t\t\t\t\tsearchRequest.setStringFilter(storage.PROPS.R_TAG, \"highway\");\n\t\t\t\t\tsearchRequest.setStringFilter(storage.PROPS.R_VALUE, \"residential\");\n//\t\t\t\t\tsearchRequest.setStringFilter(storage.PROPS.R_ADDITIONAL, \"leaf_type=broadleaved\");\n//\t\t\t\t\t searchRequest.setIntFilter(storage.PROPS.R_LAYER, 1);\n\t\t\t\t\tsearchRequest.setIntFilter(storage.PROPS.R_MINZOOM, 13);\n\t\t\t\t\tsearchRequest.setIntFilter(storage.PROPS.R_MAXZOOM, 13);\n//\t\t\t\t\t\tsearchRequest.setBooleanFilter(storage.PROPS.R_NIGHT_MODE, true);\n//\t\t\t\t\tfor (RenderingRuleProperty customProp : storage.PROPS.getCustomRules()) {\n//\t\t\t\t\t\tif (customProp.isBoolean()) {\n//\t\t\t\t\t\t\tsearchRequest.setBooleanFilter(customProp, false);\n//\t\t\t\t\t\t} else {\n//\t\t\t\t\t\t\tsearchRequest.setStringFilter(customProp, \"\");\n//\t\t\t\t\t\t}\n//\t\t\t\t\t}\n//\t\t\t\t\tsearchRequest.setBooleanFilter(storage.PROPS.get(\"noPolygons\"), true);\n\t\t\t\t\tboolean res = searchRequest.search(LINE_RULES);\n\t\t\t\t\tSystem.out.println(\"Result \" + res);\n\t\t\t\t\tprintResult(searchRequest, System.out);\n\t\t//\t\t}\n\t\t//\t\tSystem.out.println((System.nanoTime()- tm)/ (1e6f * count) );\n\t}\n\n\tprotected static void printAllRules(RenderingRulesStorage storage) {\n\t\tSystem.out.println(\"\\n\\n--------- POINTS ----- \");\n\t\tstorage.printDebug(POINT_RULES, System.out);\n\t\tSystem.out.println(\"\\n\\n--------- POLYGON ----- \");\n\t\tstorage.printDebug(POLYGON_RULES, System.out);\n\t\tSystem.out.println(\"\\n\\n--------- LINES ----- \");\n\t\tstorage.printDebug(LINE_RULES, System.out);\n\t\tSystem.out.println(\"\\n\\n--------- ORDER ----- \");\n\t\tstorage.printDebug(ORDER_RULES, System.out);\n\t\tSystem.out.println(\"\\n\\n--------- TEXT ----- \");\n\t\tstorage.printDebug(TEXT_RULES, System.out);\n\t}\n\t\n\tprivate static void printResult(RenderingRuleSearchRequest searchRequest, PrintStream out) {\n\t\tif(searchRequest.isFound()){\n\t\t\tout.print(\" Found : \");\n\t\t\tfor (RenderingRuleProperty rp : searchRequest.getProperties()) {\n\t\t\t\tif(rp.isOutputProperty() && searchRequest.isSpecified(rp)){\n\t\t\t\t\tout.print(\" \" + rp.getAttrName() + \"= \");\n\t\t\t\t\tif(rp.isString()){\n\t\t\t\t\t\tout.print(\"\\\"\" + searchRequest.getStringPropertyValue(rp) + \"\\\"\");\n\t\t\t\t\t} else if(rp.isFloat()){\n\t\t\t\t\t\tout.print(searchRequest.getFloatPropertyValue(rp));\n\t\t\t\t\t} else if(rp.isColor()){\n\t\t\t\t\t\tout.print(searchRequest.getColorStringPropertyValue(rp));\n\t\t\t\t\t} else if(rp.isIntParse()){\n\t\t\t\t\t\tout.print(searchRequest.getIntPropertyValue(rp));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tout.println(\"Not found\");\n\t\t}\n\t\t\n\t}\n}" } ]
import java.util.LinkedHashMap; import java.util.Map; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TIntObjectHashMap; import net.osmand.binary.BinaryMapIndexReader.MapIndex; import net.osmand.render.RenderingRulesStorage;
6,542
package net.osmand.binary; public class BinaryMapDataObject { protected int[] coordinates = null; protected int[][] polygonInnerCoordinates = null; protected boolean area = false; protected int[] types = null; protected int[] additionalTypes = null; protected int objectType = RenderingRulesStorage.POINT_RULES; protected TIntObjectHashMap<String> objectNames = null; protected TIntArrayList namesOrder = null; protected long id = 0;
package net.osmand.binary; public class BinaryMapDataObject { protected int[] coordinates = null; protected int[][] polygonInnerCoordinates = null; protected boolean area = false; protected int[] types = null; protected int[] additionalTypes = null; protected int objectType = RenderingRulesStorage.POINT_RULES; protected TIntObjectHashMap<String> objectNames = null; protected TIntArrayList namesOrder = null; protected long id = 0;
protected MapIndex mapIndex = null;
0
2023-11-15 05:04:55+00:00
8k
orijer/IvritInterpreter
src/Evaluation/VariableValueSwapper.java
[ { "identifier": "UnevenBracketsException", "path": "src/IvritExceptions/InterpreterExceptions/EvaluatorExceptions/UnevenBracketsException.java", "snippet": "public class UnevenBracketsException extends UncheckedIOException{\r\n public UnevenBracketsException(String str) {\r\n super(\"נמצאה שגיאה באיזון הסוגריים בקטע: \" + str, new IOException());\r\n }\r\n \r\n}\r" }, { "identifier": "BooleanVariable", "path": "src/Variables/BooleanVariable.java", "snippet": "public class BooleanVariable extends AbstractVariable<Boolean> {\r\n //An array of all the operators boolean values support:\r\n public static String[] BOOLEAN_OPERATORS = { \"שווה\", \"לא-שווה\", \"וגם\", \"או\", \">\", \"<\" };\r\n\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public BooleanVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n if (value) {\r\n return \"אמת\";\r\n }\r\n\r\n return \"שקר\";\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n if (newValue.equals(\"אמת\")) {\r\n this.value = true;\r\n } else if (newValue.equals(\"שקר\")) {\r\n this.value = false;\r\n } else {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג טענה.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked\r\n * @return true IFF checkValue is a valid boolean value in Ivrit.\r\n */\r\n public static boolean isBooleanValue(String checkValue) {\r\n return checkValue.equals(\"אמת\") || checkValue.equals(\"שקר\");\r\n }\r\n\r\n //Static methods:\r\n\r\n /**\r\n * @return true IFF the given data contains a boolean expression (that isn't in quotes, \"\"וגם\"\" doesn't count)\r\n */\r\n public static boolean containsBooleanExpression(String data) {\r\n boolean inQuotes = false;\r\n\r\n for (int index = 0; index < data.length(); index++) {\r\n if (data.charAt(index) == '\"')\r\n inQuotes = !inQuotes;\r\n else if (!inQuotes) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n //Check if the data contains an operator here that isn't in quotes:\r\n if (data.startsWith(operator, index))\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * @return 0 if the given string doesn't start with a boolean operatorm or the operator length (how many characters it has) otherwise.\r\n */\r\n public static int startsWithBooleanOperator(String data) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n if (data.startsWith(operator))\r\n return operator.length();\r\n }\r\n\r\n return 0;\r\n }\r\n}\r" }, { "identifier": "FloatVariable", "path": "src/Variables/FloatVariable.java", "snippet": "public class FloatVariable extends AbstractVariable<Float> implements NumericVariable {\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public FloatVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n return Float.toString(this.value);\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n try {\r\n this.value = Float.parseFloat(newValue);\r\n } catch (NumberFormatException exception) {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג עשרוני.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked.\r\n * @return true IFF checkValue is a valid float value in Ivrit.\r\n */\r\n public static boolean isFloatValue(String checkValue) {\r\n try {\r\n Float.parseFloat(checkValue);\r\n return true;\r\n } catch (NumberFormatException exception) {\r\n return false;\r\n }\r\n }\r\n\r\n //NumericVariable methods:\r\n\r\n @Override\r\n public void add(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value += Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value += Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחבר למשתנה מסוג עשרוני את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void substract(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value -= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value -= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחסר ממשתנה מסוג עשרוני את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void multiply(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value *= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value *= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן להכפיל משתנה מסוג עשרוני בערך \" + value);\r\n }\r\n\r\n @Override\r\n public void divide(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value /= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value /= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחלק משתנה מסוג עשרוני בערך \" + value);\r\n }\r\n\r\n @Override\r\n public BooleanVariable greaterThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value > Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value > Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג עשרוני לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n\r\n @Override\r\n public BooleanVariable lessThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value < Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value < Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג עשרוני לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n}\r" }, { "identifier": "IntegerVariable", "path": "src/Variables/IntegerVariable.java", "snippet": "public class IntegerVariable extends AbstractVariable<Integer> implements NumericVariable { \r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public IntegerVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n return Integer.toString(this.value);\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n try {\r\n this.value = Integer.parseInt(newValue);\r\n } catch (NumberFormatException exception) {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג שלם.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked.\r\n * @return true IFF checkValue is a valid integer value in Ivrit.\r\n */\r\n public static boolean isIntegerValue(String checkValue) {\r\n try {\r\n Integer.parseInt(checkValue);\r\n return true;\r\n } catch (NumberFormatException exception) {\r\n return false;\r\n }\r\n }\r\n\r\n //NumericVariable methods:\r\n\r\n @Override\r\n public void add(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value += Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value += (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחבר למשתנה מסוג שלם את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void substract(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value -= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value -= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחסר ממשתנה מסוג שלם את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void multiply(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value *= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value *= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להכפיל משתנה מסוג שלם בערך \" + value);\r\n }\r\n\r\n @Override\r\n public void divide(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value /= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value /= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחלק משתנה מסוג שלם בערך \" + value);\r\n }\r\n\r\n @Override\r\n public BooleanVariable greaterThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value > Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value > Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג שלם לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n\r\n @Override\r\n public BooleanVariable lessThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value < Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value < Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג שלם לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n}\r" }, { "identifier": "NumericVariable", "path": "src/Variables/NumericVariable.java", "snippet": "public interface NumericVariable extends Variable {\r\n //An array of all the operators Numeric Variables support:\r\n public static char[] NUMERIC_OPERATORS = { '+', '-', '*', '/' };\r\n\r\n /**\r\n * Adds the given value to the variable's value.\r\n * @param value - The value to be added (represented as a string).\r\n */\r\n public void add(String value);\r\n\r\n /**\r\n * Substracts the given value from the variable's value.\r\n * @param value - The value to substract (represented as a string).\r\n */\r\n public void substract(String value);\r\n\r\n /**\r\n * Multiplies the variable's value by the given value.\r\n * @param value - The value to multiply by (represented as a string).\r\n */\r\n public void multiply(String value);\r\n\r\n /**\r\n * Divides the variable's value by the given value.\r\n * @param value - The value to divide by (represented as a string).\r\n */\r\n public void divide(String value);\r\n\r\n /**\r\n * @return true IFF the variable's value is greater then the given value.\r\n */\r\n public BooleanVariable greaterThen(String value);\r\n\r\n /**\r\n * @return true IFF the variable's value is less then the given value.\r\n */\r\n public BooleanVariable lessThen(String value);\r\n //Static methods:\r\n\r\n /**\r\n * @return true IFF the given char is a numeric operator (as declared in the static field OPERATORS in this class).\r\n */\r\n public static boolean isNumericOperator(char ch) {\r\n for (char operator : NumericVariable.NUMERIC_OPERATORS) {\r\n if (ch == operator)\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * @return how many numeric operators are in the given string.\r\n */\r\n public static int countNumericOperators(String str) {\r\n String regex = \"\\\\+|-|\\\\*|/\";\r\n\r\n String[] parts = str.split(regex);\r\n\r\n return parts.length - 1;\r\n }\r\n}\r" }, { "identifier": "VariablesController", "path": "src/Variables/VariablesController.java", "snippet": "public class VariablesController {\r\n //A map that connects between the name of the variable to its value:\r\n private Map<String, Variable> dataMap;\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public VariablesController() {\r\n this.dataMap = new HashMap<>();\r\n }\r\n\r\n /**\r\n * @param name - The name of the variable to check.\r\n * @return true IFF there is already a variable with the given name stored.\r\n */\r\n public boolean isVariable(String name) {\r\n return this.dataMap.containsKey(name);\r\n }\r\n\r\n /**\r\n * Creates a new variable.\r\n * @param variableName - The name of the new variable.\r\n * @param variableType - The type of the new variable.\r\n * @param variableValue - the value of the new variable.\r\n */\r\n public void createVariable(String variableName, String variableType, String variableValue) {\r\n Variable variable;\r\n if (this.dataMap.containsKey(variableValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable = VariablesFactory.createVariable(variableType, this.dataMap.get(variableValue).getValue());\r\n\r\n } else {\r\n //We are creating a variable from the value:\r\n variable = VariablesFactory.createVariable(variableType, variableValue);\r\n\r\n }\r\n\r\n this.dataMap.put(variableName, variable);\r\n }\r\n\r\n /**\r\n * Deletes the given variable from the program.\r\n * @param variableName - The name of the variable to delete.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void deleteVariable(String variableName) {\r\n if (!this.dataMap.containsKey(variableName))\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n\r\n this.dataMap.remove(variableName);\r\n }\r\n\r\n /**\r\n * Updates the value of an existing variable.\r\n * @param variableName - The name of the variable to be updated.\r\n * @param newValue - The new value.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void updateVariable(String variableName, String newValue) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n if (this.dataMap.containsKey(newValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable.updateValue(this.dataMap.get(newValue).getValue());\r\n } else {\r\n //We are updating from the value:\r\n variable.updateValue(newValue);\r\n\r\n }\r\n }\r\n\r\n /**\r\n * @param variableName - The name of the variable we wan the value of.\r\n * @return the value of the variable with the given name.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public String getVariableValue(String variableName) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n return variable.getValue();\r\n }\r\n\r\n /**\r\n * Clears all the variables created.\r\n */\r\n public void clear() {\r\n this.dataMap.clear();\r\n }\r\n\r\n /**\r\n * Prints all the variables in the format (variableName : variableValue).\r\n */\r\n public void printVariables() {\r\n for (Map.Entry<String, Variable> entry : this.dataMap.entrySet()) {\r\n System.out.println(\"(\" + entry.getKey() + \" : \" + entry.getValue().toString() + \")\");\r\n }\r\n }\r\n}\r" } ]
import java.io.IOException; import java.io.UncheckedIOException; import IvritExceptions.InterpreterExceptions.EvaluatorExceptions.UnevenBracketsException; import Variables.BooleanVariable; import Variables.FloatVariable; import Variables.IntegerVariable; import Variables.NumericVariable; import Variables.VariablesController;
4,979
package Evaluation; /** * Handles switching the variables with their values for the evaluation. */ public class VariableValueSwapper { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - The object that handles the variables of the program. */ public VariableValueSwapper(VariablesController variablesController) { this.variablesController = variablesController; } /** * Reads through a given data string and switches every occurence of a variable with its correct value. * @param data - The data to process. * @return a new string that is similar to the given string, but every occurence of a variable is switched with its value. */ public String swap(String originalData) { String data = originalData; //We want to keep the original data to be used when throwing an exception. StringBuilder swappedLine = new StringBuilder(); int endAt; while (data.length() > 0) { char firstChar = data.charAt(0); if (firstChar == '"') { data = copyStringLiteral(data, swappedLine, originalData); } else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) { //We are reading a space, a bracket, or an operator, just copy it: swappedLine.append(firstChar); data = data.substring(1); } else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) { //We are reading a boolean operator: swappedLine.append(data.substring(0, endAt)); data = data.substring(endAt); } else { //We are reading a literal (non-string) value or a variable: endAt = dataEndAt(data); String literalValueOrVariable = data.substring(0, endAt); if (this.variablesController.isVariable(literalValueOrVariable)) { //If it is a variable, switch it with its value: swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable)); } else { //If it is literal data, try to copy it: copyNonStringLiteral(literalValueOrVariable, swappedLine); } data = data.substring(endAt); } } return swappedLine.toString(); } /** * If given a valid string literal, add its value to the given StringBuilder, * and return the data without the string literal that was found. * @param data - The data that should start with a string literal. * @param swappedLine - The StringBuilder we build the evaluated result in. * @return a substring of the given data string that starts after the string literal that was found. */ private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) { int endAt = data.indexOf('"', 1); if (endAt == -1) {
package Evaluation; /** * Handles switching the variables with their values for the evaluation. */ public class VariableValueSwapper { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - The object that handles the variables of the program. */ public VariableValueSwapper(VariablesController variablesController) { this.variablesController = variablesController; } /** * Reads through a given data string and switches every occurence of a variable with its correct value. * @param data - The data to process. * @return a new string that is similar to the given string, but every occurence of a variable is switched with its value. */ public String swap(String originalData) { String data = originalData; //We want to keep the original data to be used when throwing an exception. StringBuilder swappedLine = new StringBuilder(); int endAt; while (data.length() > 0) { char firstChar = data.charAt(0); if (firstChar == '"') { data = copyStringLiteral(data, swappedLine, originalData); } else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) { //We are reading a space, a bracket, or an operator, just copy it: swappedLine.append(firstChar); data = data.substring(1); } else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) { //We are reading a boolean operator: swappedLine.append(data.substring(0, endAt)); data = data.substring(endAt); } else { //We are reading a literal (non-string) value or a variable: endAt = dataEndAt(data); String literalValueOrVariable = data.substring(0, endAt); if (this.variablesController.isVariable(literalValueOrVariable)) { //If it is a variable, switch it with its value: swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable)); } else { //If it is literal data, try to copy it: copyNonStringLiteral(literalValueOrVariable, swappedLine); } data = data.substring(endAt); } } return swappedLine.toString(); } /** * If given a valid string literal, add its value to the given StringBuilder, * and return the data without the string literal that was found. * @param data - The data that should start with a string literal. * @param swappedLine - The StringBuilder we build the evaluated result in. * @return a substring of the given data string that starts after the string literal that was found. */ private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) { int endAt = data.indexOf('"', 1); if (endAt == -1) {
throw new UnevenBracketsException(originalData);
0
2023-11-17 09:15:07+00:00
8k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmEmployeeSocialSecurityController.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnum behavior = null;\n\n private OperateObjectEnum applyObject = null;\n\n private ApplyEnum apply = null;\n\n public void setOperationObject(Object typeId, Object typeName) {\n if (operationObject == null) {\n this.operationObject = new JSONObject();\n }\n if (operationObject instanceof JSONObject) {\n ((JSONObject) operationObject).put(\"typeId\", String.valueOf(typeId));\n ((JSONObject) operationObject).put(\"typeName\", typeName);\n }\n\n }\n\n public void setOperationObject(String key, Object value) {\n if (operationObject == null) {\n operationObject = new JSONObject();\n }\n if (operationObject instanceof JSONObject) {\n ((JSONObject) operationObject).put(key, value);\n }\n }\n\n}" }, { "identifier": "OperationResult", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationResult.java", "snippet": "@Getter\n@Setter\npublic class OperationResult<T> extends Result<T> {\n\n private static final long serialVersionUID = 1L;\n\n private List<OperationLog> operationLogs;\n\n public OperationResult(ResultCode resultCode) {\n super(resultCode);\n }\n\n public static <T> OperationResult<T> ok(T data, List<OperationLog> operationLogs) {\n OperationResult<T> result = new OperationResult<>(SystemCodeEnum.SYSTEM_OK);\n result.setData(data);\n if (operationLogs == null) {\n return result;\n }\n operationLogs = operationLogs.stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());\n result.setOperationLogs(operationLogs);\n return result;\n }\n\n public static <T> OperationResult<T> ok(List<OperationLog> operationLogs) {\n OperationResult<T> result = new OperationResult<>(SystemCodeEnum.SYSTEM_OK);\n if (operationLogs == null) {\n return result;\n }\n operationLogs = operationLogs.stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());\n result.setOperationLogs(operationLogs);\n return result;\n }\n\n public static <T> OperationResult<T> ok(OperationLog operationLogs) {\n return ok(ListUtil.toList(operationLogs));\n }\n\n\n public static <T> OperationResult error(ResultCode resultCode, List<OperationLog> operationLogs) {\n OperationResult<T> result = new OperationResult<>(resultCode);\n result.setOperationLogs(operationLogs);\n return result;\n }\n}" }, { "identifier": "Result", "path": "common/common-web/src/main/java/com/kakarote/core/common/Result.java", "snippet": "public class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"code\", required = true, example = \"0\")\n private Integer code;\n\n @ApiModelProperty(value = \"msg\", required = true, example = \"success\")\n private String msg;\n\n private T data;\n\n Result() {\n\n }\n\n\n protected Result(ResultCode resultCode) {\n this.code = resultCode.getCode();\n this.msg = resultCode.getMsg();\n }\n\n private Result(ResultCode resultCode, String msg) {\n this.code = resultCode.getCode();\n this.msg = msg;\n }\n\n private Result(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n\n public Integer getCode() {\n return code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n\n public static Result<String> noAuth() {\n return error(SystemCodeEnum.SYSTEM_NO_AUTH);\n }\n\n public static <T> Result<T> error(ResultCode resultCode) {\n return new Result<>(resultCode);\n }\n\n public static <T> Result<T> error(int code, String msg) {\n return new Result<>(code, msg);\n }\n\n public static <T> Result<T> error(ResultCode resultCode, String msg) {\n return new Result<T>(resultCode, msg);\n }\n\n public static <T> Result<T> ok(T data) {\n Result<T> result = new Result<>(SystemCodeEnum.SYSTEM_OK);\n result.setData(data);\n return result;\n }\n\n\n public static <T> Result<T> ok() {\n return new Result<T>(SystemCodeEnum.SYSTEM_OK);\n }\n\n\n public Result<T> setData(T data) {\n this.data = data;\n return this;\n }\n\n public T getData() {\n return this.data;\n }\n\n public boolean hasSuccess() {\n return Objects.equals(SystemCodeEnum.SYSTEM_OK.getCode(), code);\n }\n\n public String toJSONString() {\n return JSON.toJSONString(this);\n }\n\n @Override\n public String toString() {\n return toJSONString();\n }\n\n\n\n}" }, { "identifier": "BasePage", "path": "common/common-web/src/main/java/com/kakarote/core/entity/BasePage.java", "snippet": "public class BasePage<T> implements IPage<T> {\n\n private static final long serialVersionUID = 8545996863226528798L;\n\n /**\n * 查询数据列表\n */\n private List<T> list;\n\n /**\n * 总数\n */\n private long totalRow;\n\n /**\n * 每页显示条数,默认 15\n */\n private long pageSize;\n\n /**\n * 当前页\n */\n private long pageNumber;\n\n /**\n * 排序字段信息\n */\n private List<OrderItem> orders;\n\n /**\n * 自动优化 COUNT SQL\n */\n private boolean optimizeCountSql;\n\n\n /**\n * 额外数据\n */\n private Object extraData;\n\n\n public BasePage() {\n this(null, null);\n }\n\n /**\n * 分页构造函数\n *\n * @param current 当前页\n * @param size 每页显示条数\n */\n public BasePage(Long current, Long size) {\n this(current, size, 0L);\n }\n\n /**\n * 分页构造函数\n *\n * @param current 当前页\n * @param size 每页显示条数\n * @param total 总行数\n */\n public BasePage(Long current, Long size, Long total) {\n this(current, size, total, new ArrayList<>());\n }\n\n /**\n * @param current 当前页\n * @param size 每页显示条数\n * @param total 总行数\n * @param list 数据列表\n */\n public BasePage(Long current, Long size, Long total, List<T> list) {\n if (current == null || current < 0L) {\n current = 1L;\n }\n if (size == null || size < 0L) {\n size = 15L;\n }\n if (total == null || total < 0L) {\n total = 0L;\n }\n\n this.pageNumber = current;\n this.pageSize = size;\n this.totalRow = total;\n this.orders = new ArrayList<>();\n this.optimizeCountSql = true;\n this.list = list;\n }\n\n\n @Override\n @JsonIgnore\n public List<T> getRecords() {\n return this.list;\n }\n\n public List<T> getList() {\n return this.list;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getTotalRow() {\n return this.totalRow;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getTotalPage() {\n if (getSize() == 0) {\n return 0L;\n }\n long pages = getTotal() / getSize();\n if (getTotal() % getSize() != 0) {\n pages++;\n }\n return pages;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getPageSize() {\n return this.pageSize;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getPageNumber() {\n return this.pageNumber;\n }\n\n public boolean isFirstPage() {\n return this.pageNumber == 1L;\n }\n\n public boolean isLastPage() {\n return getTotal() == 0 || this.pageNumber >= getTotalPage();\n }\n\n public void setPageNumber(long pageNumber) {\n this.pageNumber = pageNumber;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n @Override\n public BasePage<T> setRecords(List<T> records) {\n this.list = records;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getTotal() {\n return this.totalRow;\n }\n\n @Override\n public BasePage<T> setTotal(long total) {\n this.totalRow = total;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getSize() {\n return this.pageSize;\n }\n\n @Override\n public BasePage<T> setSize(long size) {\n this.pageSize = size;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getCurrent() {\n return this.pageNumber;\n }\n\n @Override\n public BasePage<T> setCurrent(long current) {\n this.pageNumber = current;\n return this;\n }\n\n\n @Override\n public List<OrderItem> orders() {\n return orders;\n }\n\n public void setOrders(List<OrderItem> orders) {\n this.orders = orders;\n }\n\n public List<OrderItem> getOrders() {\n return orders;\n }\n\n @Override\n public boolean optimizeCountSql() {\n return optimizeCountSql;\n }\n\n\n public BasePage<T> setOptimizeCountSql(boolean optimizeCountSql) {\n this.optimizeCountSql = optimizeCountSql;\n return this;\n }\n\n /**\n * 类型转换 通过beanCopy\n *\n * @param clazz 转换后的类\n * @param <R> R\n * @return BasePage\n */\n public <R> BasePage<R> copy(Class<R> clazz) {\n return copy(obj -> BeanUtil.copyProperties(obj, clazz));\n }\n\n /**\n * 类型转换 通过beanCopy\n *\n * @param <R> R\n * @return BasePage\n */\n public <R> BasePage<R> copy(Function<? super T, ? extends R> mapper) {\n BasePage<R> basePage = new BasePage<>(getCurrent(), getSize(), getTotal());\n basePage.setRecords(getRecords().stream().map(mapper).collect(Collectors.toList()));\n return basePage;\n }\n\n @Override\n @JsonIgnore\n public long getPages() {\n return getTotalPage();\n }\n\n public Object getExtraData() {\n return extraData;\n }\n\n public void setExtraData(Object extraData) {\n this.extraData = extraData;\n }\n}" }, { "identifier": "QuerySalaryListBO", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/BO/QuerySalaryListBO.java", "snippet": "@Getter\n@Setter\npublic class QuerySalaryListBO extends PageEntity {\n\n private Long employeeId;\n\n @Override\n public String toString() {\n return \"QuerySalaryListBO{\" +\n \"employeeId=\" + employeeId +\n '}';\n }\n}" }, { "identifier": "HrmEmployeeSalaryCard", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/PO/HrmEmployeeSalaryCard.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"wk_hrm_employee_salary_card\")\n@ApiModel(value = \"HrmEmployeeSalaryCard对象\", description = \"员工薪资卡信息\")\npublic class HrmEmployeeSalaryCard implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"salary_card_id\", type = IdType.ASSIGN_ID)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long salaryCardId;\n\n @JsonSerialize(using = ToStringSerializer.class)\n private Long employeeId;\n\n @ApiModelProperty(value = \"工资卡卡号\")\n private String salaryCardNum;\n\n @ApiModelProperty(value = \"开户城市\")\n private String accountOpeningCity;\n\n @ApiModelProperty(value = \"银行名称\")\n private String bankName;\n\n @ApiModelProperty(value = \"工资卡开户行\")\n private String openingBank;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n @TableField(fill = FieldFill.INSERT)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long createUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long updateUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n private LocalDateTime updateTime;\n\n}" }, { "identifier": "HrmEmployeeSocialSecurityInfo", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/PO/HrmEmployeeSocialSecurityInfo.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"wk_hrm_employee_social_security_info\")\n@ApiModel(value = \"HrmEmployeeSocialSecurityInfo对象\", description = \"员工公积金信息\")\npublic class HrmEmployeeSocialSecurityInfo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"social_security_info_id\", type = IdType.ASSIGN_ID)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long socialSecurityInfoId;\n\n @JsonSerialize(using = ToStringSerializer.class)\n private Long employeeId;\n\n @ApiModelProperty(value = \"是否首次缴纳社保 0 否 1 是\")\n private Integer isFirstSocialSecurity;\n\n @ApiModelProperty(value = \"是否首次缴纳公积金 0 否 1 是\")\n private Integer isFirstAccumulationFund;\n\n @ApiModelProperty(value = \"社保号\")\n private String socialSecurityNum;\n\n @ApiModelProperty(value = \"公积金账号\")\n private String accumulationFundNum;\n\n @ApiModelProperty(value = \"参保起始月份(2020.05)\")\n private String socialSecurityStartMonth;\n\n @ApiModelProperty(value = \"参保方案\")\n @JsonSerialize(using = ToStringSerializer.class)\n private Long schemeId;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n @TableField(fill = FieldFill.INSERT)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long createUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long updateUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n private LocalDateTime updateTime;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"参保方案名称\")\n private String schemeName;\n\n\n}" }, { "identifier": "QuerySalaryListVO", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/VO/QuerySalaryListVO.java", "snippet": "@Getter\n@Setter\npublic class QuerySalaryListVO {\n\n private Long sEmpRecordId;\n\n @ApiModelProperty(\"年\")\n private Integer year;\n\n @ApiModelProperty(\"月\")\n private Integer month;\n\n @ApiModelProperty(\"开始日期\")\n @JsonFormat(pattern = \"yyyy-MM-dd\")\n private LocalDateTime startTime;\n\n @ApiModelProperty(\"结束日期\")\n @JsonFormat(pattern = \"yyyy-MM-dd\")\n private LocalDateTime endTime;\n\n @ApiModelProperty(\"应发工资\")\n private String shouldSalary;\n\n @ApiModelProperty(\"个人所得税\")\n private String personalTax;\n\n @ApiModelProperty(\"实发工资\")\n private String realSalary;\n\n @Override\n public String toString() {\n return \"QuerySalaryListVO{\" +\n \"sEmpRecordId=\" + sEmpRecordId +\n \", year=\" + year +\n \", month=\" + month +\n \", startTime=\" + startTime +\n \", endTime=\" + endTime +\n \", shouldSalary='\" + shouldSalary + '\\'' +\n \", personalTax='\" + personalTax + '\\'' +\n \", realSalary='\" + realSalary + '\\'' +\n '}';\n }\n}" }, { "identifier": "SalaryOptionHeadVO", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/VO/SalaryOptionHeadVO.java", "snippet": "@Setter\n@Getter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class SalaryOptionHeadVO {\n\n @ApiModelProperty(\"薪资项code\")\n private Integer code;\n\n @ApiModelProperty(\"薪资项名称\")\n private String name;\n\n @ApiModelProperty(\"薪资项名称\")\n private Integer isFixed;\n\n @ApiModelProperty(\"值\")\n private String value;\n\n @ApiModelProperty(value = \"语言包map\")\n private Map<String, String> languageKeyMap;\n\n public SalaryOptionHeadVO(Integer code, String name, Integer isFixed) {\n this.code = code;\n this.name = name;\n this.isFixed = isFixed;\n }\n\n @Override\n public String toString() {\n return \"SalaryOptionHeadVO{\" +\n \"code=\" + code +\n \", name='\" + name + '\\'' +\n \", isFixed=\" + isFixed +\n \", value='\" + value + '\\'' +\n '}';\n }\n}" }, { "identifier": "SalarySocialSecurityVO", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/VO/SalarySocialSecurityVO.java", "snippet": "@Data\n@AllArgsConstructor\npublic class SalarySocialSecurityVO {\n\n @ApiModelProperty(\"工资卡信息\")\n private HrmEmployeeSalaryCard salaryCard;\n\n @ApiModelProperty(\"社保信息\")\n private HrmEmployeeSocialSecurityInfo socialSecurityInfo;\n}" }, { "identifier": "IHrmEmployeeSocialSecurityService", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/service/IHrmEmployeeSocialSecurityService.java", "snippet": "public interface IHrmEmployeeSocialSecurityService extends BaseService<HrmEmployeeSocialSecurityInfo> {\n\n /**\n * 工资社保基本信息\n *\n * @param employeeId\n * @return\n */\n SalarySocialSecurityVO salarySocialSecurityInformation(Long employeeId);\n\n /**\n * 添加修改工资卡\n *\n * @param salaryCard\n */\n void addOrUpdateSalaryCard(HrmEmployeeSalaryCard salaryCard);\n\n /**\n * 删除工资卡\n *\n * @param salaryCardId\n */\n void deleteSalaryCard(Long salaryCardId);\n\n /**\n * 添加修改社保信息\n *\n * @param socialSecurityInfo\n */\n OperationLog addOrUpdateSocialSecurity(HrmEmployeeSocialSecurityInfo socialSecurityInfo);\n\n /**\n * 删除社保\n *\n * @param socialSecurityInfoId\n */\n void deleteSocialSecurity(Long socialSecurityInfoId);\n\n /**\n * 查询薪资列表\n *\n * @param querySalaryListBO\n * @return\n */\n BasePage<QuerySalaryListVO> querySalaryList(QuerySalaryListBO querySalaryListBO);\n\n /**\n * 查询薪资详情\n *\n * @param sEmpRecordId\n * @return\n */\n List<SalaryOptionHeadVO> querySalaryDetail(String sEmpRecordId);\n}" } ]
import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.core.common.Result; import com.kakarote.core.entity.BasePage; import com.kakarote.hrm.entity.BO.QuerySalaryListBO; import com.kakarote.hrm.entity.PO.HrmEmployeeSalaryCard; import com.kakarote.hrm.entity.PO.HrmEmployeeSocialSecurityInfo; import com.kakarote.hrm.entity.VO.QuerySalaryListVO; import com.kakarote.hrm.entity.VO.SalaryOptionHeadVO; import com.kakarote.hrm.entity.VO.SalarySocialSecurityVO; import com.kakarote.hrm.service.IHrmEmployeeSocialSecurityService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
5,644
package com.kakarote.hrm.controller; /** * <p> * 员工工资社保 * </p> * * @author huangmingbo * @since 2020-05-12 */ @RestController @RequestMapping("/hrmEmployee/SocialSecurity") @Api(tags = "员工管理-员工工资社保") public class HrmEmployeeSocialSecurityController { @Autowired private IHrmEmployeeSocialSecurityService socialSecurityService; @PostMapping("/salarySocialSecurityInformation/{employeeId}") @ApiOperation("工资社保基本信息") public Result<SalarySocialSecurityVO> salarySocialSecurityInformation(@PathVariable("employeeId") Long employeeId) { SalarySocialSecurityVO salarySocialSecurityVO = socialSecurityService.salarySocialSecurityInformation(employeeId); return Result.ok(salarySocialSecurityVO); } @PostMapping("/addSalaryCard") @ApiOperation("添加工资卡") public Result addSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) { socialSecurityService.addOrUpdateSalaryCard(salaryCard); return Result.ok(); } @PostMapping("/setSalaryCard") @ApiOperation("修改工资卡") public Result setSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) { socialSecurityService.addOrUpdateSalaryCard(salaryCard); return Result.ok(); } /** * 删除工资卡 */ @PostMapping("/deleteSalaryCard/{salaryCardId}") @ApiOperation("删除工资卡") public Result deleteSalaryCard(@PathVariable("salaryCardId") Long salaryCardId) { socialSecurityService.deleteSalaryCard(salaryCardId); return Result.ok(); } @PostMapping("/addSocialSecurity") @ApiOperation("添加社保信息") public Result addSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) { socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo); return Result.ok(); } @PostMapping("/setSocialSecurity") @ApiOperation("修改社保信息") @OperateLog() public Result setSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) { OperationLog operationLog = socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo); return OperationResult.ok(operationLog); } @PostMapping("/deleteSocialSecurity/{socialSecurityInfoId}") @ApiOperation("删除社保信息") public Result deleteSocialSecurity(@PathVariable("socialSecurityInfoId") Long socialSecurityInfoId) { socialSecurityService.deleteSocialSecurity(socialSecurityInfoId); return Result.ok(); } @PostMapping("/querySalaryList") @ApiOperation("查询薪资列表")
package com.kakarote.hrm.controller; /** * <p> * 员工工资社保 * </p> * * @author huangmingbo * @since 2020-05-12 */ @RestController @RequestMapping("/hrmEmployee/SocialSecurity") @Api(tags = "员工管理-员工工资社保") public class HrmEmployeeSocialSecurityController { @Autowired private IHrmEmployeeSocialSecurityService socialSecurityService; @PostMapping("/salarySocialSecurityInformation/{employeeId}") @ApiOperation("工资社保基本信息") public Result<SalarySocialSecurityVO> salarySocialSecurityInformation(@PathVariable("employeeId") Long employeeId) { SalarySocialSecurityVO salarySocialSecurityVO = socialSecurityService.salarySocialSecurityInformation(employeeId); return Result.ok(salarySocialSecurityVO); } @PostMapping("/addSalaryCard") @ApiOperation("添加工资卡") public Result addSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) { socialSecurityService.addOrUpdateSalaryCard(salaryCard); return Result.ok(); } @PostMapping("/setSalaryCard") @ApiOperation("修改工资卡") public Result setSalaryCard(@RequestBody HrmEmployeeSalaryCard salaryCard) { socialSecurityService.addOrUpdateSalaryCard(salaryCard); return Result.ok(); } /** * 删除工资卡 */ @PostMapping("/deleteSalaryCard/{salaryCardId}") @ApiOperation("删除工资卡") public Result deleteSalaryCard(@PathVariable("salaryCardId") Long salaryCardId) { socialSecurityService.deleteSalaryCard(salaryCardId); return Result.ok(); } @PostMapping("/addSocialSecurity") @ApiOperation("添加社保信息") public Result addSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) { socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo); return Result.ok(); } @PostMapping("/setSocialSecurity") @ApiOperation("修改社保信息") @OperateLog() public Result setSocialSecurity(@RequestBody HrmEmployeeSocialSecurityInfo socialSecurityInfo) { OperationLog operationLog = socialSecurityService.addOrUpdateSocialSecurity(socialSecurityInfo); return OperationResult.ok(operationLog); } @PostMapping("/deleteSocialSecurity/{socialSecurityInfoId}") @ApiOperation("删除社保信息") public Result deleteSocialSecurity(@PathVariable("socialSecurityInfoId") Long socialSecurityInfoId) { socialSecurityService.deleteSocialSecurity(socialSecurityInfoId); return Result.ok(); } @PostMapping("/querySalaryList") @ApiOperation("查询薪资列表")
public Result<BasePage<QuerySalaryListVO>> querySalaryList(@RequestBody QuerySalaryListBO querySalaryListBO) {
3
2023-10-17 05:49:52+00:00
8k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/utils/CodeShellUtils.java
[ { "identifier": "PrefixString", "path": "src/main/java/com/codeshell/intellij/constant/PrefixString.java", "snippet": "public interface PrefixString {\n\n String EXPLAIN_CODE = \"请解释以下%s代码: %s\";\n\n String OPTIMIZE_CODE = \"请优化以下%s代码: %s\";\n\n String CLEAN_CODE = \"请清理以下%s代码: %s\";\n\n String COMMENT_CODE = \"请为以下%s代码的每一行生成注释: %s\";\n\n String UNIT_TEST_CODE = \"请为以下%s代码生成单元测试: %s\";\n\n String PERFORMANCE_CODE = \"检查以下%s代码,是否存在性能问题,请给出优化建议: %s\";\n\n String STYLE_CODE = \"检查以下%s代码的风格样式,请给出优化建议: %s\";\n\n String SECURITY_CODE = \"检查以下%s代码,是否存在安全性问题,请给出优化建议: %s\";\n\n String MARKDOWN_CODE_FIX = \"```\";\n\n String REQUST_END_TAG = \"|<end>|\";\n\n String RESPONSE_END_TAG = \"<|endoftext|>\";\n}" }, { "identifier": "GenerateModel", "path": "src/main/java/com/codeshell/intellij/model/GenerateModel.java", "snippet": "public class GenerateModel {\n\n private String generated_text;\n\n public String getGenerated_text() {\n return generated_text;\n }\n\n public void setGenerated_text(String generated_text) {\n this.generated_text = generated_text;\n }\n}" }, { "identifier": "CodeShellSettings", "path": "src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java", "snippet": "@State(name = \"CodeShellSettings\", storages = @Storage(\"codeshell_settings.xml\"))\npublic class CodeShellSettings implements PersistentStateComponent<Element> {\n public static final String SETTINGS_TAG = \"CodeShellSettings\";\n private static final String SERVER_ADDRESS_TAG = \"SERVER_ADDRESS_URL\";\n private static final String SAYT_TAG = \"SAYT_ENABLED\";\n private static final String CPU_RADIO_BUTTON_TAG = \"CPU_RADIO_BUTTON_ENABLED\";\n private static final String GPU_RADIO_BUTTON_TAG = \"GPU_RADIO_BUTTON_ENABLED\";\n private static final String TAB_ACTION_TAG = \"TAB_ACTION\";\n private static final String COMPLETION_MAX_TOKENS_TAG = \"COMPLETION_MAX_TOKENS\";\n private static final String CHAT_MAX_TOKENS_TAG = \"CHAT_MAX_TOKENS\";\n private boolean saytEnabled = true;\n private boolean cpuRadioButtonEnabled = true;\n private boolean gpuRadioButtonEnabled = false;\n private String serverAddressURL = \"http://127.0.0.1:8080\";\n private TabActionOption tabActionOption = TabActionOption.ALL;\n private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM;\n private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM;\n\n private static final CodeShellSettings SHELL_CODER_SETTINGS_INSTANCE = new CodeShellSettings();\n\n @Override\n public @Nullable Element getState() {\n Element state = new Element(SETTINGS_TAG);\n state.setAttribute(CPU_RADIO_BUTTON_TAG, Boolean.toString(isCPURadioButtonEnabled()));\n state.setAttribute(GPU_RADIO_BUTTON_TAG, Boolean.toString(isGPURadioButtonEnabled()));\n state.setAttribute(SERVER_ADDRESS_TAG, getServerAddressURL());\n state.setAttribute(SAYT_TAG, Boolean.toString(isSaytEnabled()));\n state.setAttribute(TAB_ACTION_TAG, getTabActionOption().name());\n state.setAttribute(COMPLETION_MAX_TOKENS_TAG, getCompletionMaxToken().name());\n state.setAttribute(CHAT_MAX_TOKENS_TAG, getChatMaxToken().name());\n return state;\n }\n\n @Override\n public void loadState(@NotNull Element state) {\n if (Objects.nonNull(state.getAttributeValue(CPU_RADIO_BUTTON_TAG))) {\n setCPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(CPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(GPU_RADIO_BUTTON_TAG))) {\n setGPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(GPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(SERVER_ADDRESS_TAG))) {\n setServerAddressURL(state.getAttributeValue(SERVER_ADDRESS_TAG));\n }\n if (Objects.nonNull(state.getAttributeValue(SAYT_TAG))) {\n setSaytEnabled(Boolean.parseBoolean(state.getAttributeValue(SAYT_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(TAB_ACTION_TAG))) {\n setTabActionOption(TabActionOption.valueOf(state.getAttributeValue(TAB_ACTION_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG))) {\n setCompletionMaxToken(CompletionMaxToken.valueOf(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(CHAT_MAX_TOKENS_TAG))) {\n setChatMaxToken(ChatMaxToken.valueOf(state.getAttributeValue(CHAT_MAX_TOKENS_TAG)));\n }\n }\n\n public static CodeShellSettings getInstance() {\n if (Objects.isNull(ApplicationManager.getApplication())) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n\n CodeShellSettings service = ApplicationManager.getApplication().getService(CodeShellSettings.class);\n if (Objects.isNull(service)) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n return service;\n }\n\n public boolean isSaytEnabled() {\n return saytEnabled;\n }\n\n public void setSaytEnabled(boolean saytEnabled) {\n this.saytEnabled = saytEnabled;\n }\n\n public void toggleSaytEnabled() {\n this.saytEnabled = !this.saytEnabled;\n }\n\n public boolean isCPURadioButtonEnabled() {\n return cpuRadioButtonEnabled;\n }\n\n public void setCPURadioButtonEnabled(boolean cpuRadioButtonEnabled) {\n this.cpuRadioButtonEnabled = cpuRadioButtonEnabled;\n }\n\n public boolean isGPURadioButtonEnabled() {\n return gpuRadioButtonEnabled;\n }\n\n public void setGPURadioButtonEnabled(boolean gpuRadioButtonEnabled) {\n this.gpuRadioButtonEnabled = gpuRadioButtonEnabled;\n }\n\n public String getServerAddressURL() {\n return serverAddressURL;\n }\n\n public void setServerAddressURL(String serverAddressURL) {\n this.serverAddressURL = serverAddressURL;\n }\n\n public CompletionMaxToken getCompletionMaxToken() {\n return completionMaxToken;\n }\n\n public void setCompletionMaxToken(CompletionMaxToken completionMaxToken) {\n this.completionMaxToken = completionMaxToken;\n }\n\n public ChatMaxToken getChatMaxToken() {\n return chatMaxToken;\n }\n\n public void setChatMaxToken(ChatMaxToken chatMaxToken) {\n this.chatMaxToken = chatMaxToken;\n }\n\n public TabActionOption getTabActionOption() {\n return tabActionOption;\n }\n\n public void setTabActionOption(TabActionOption tabActionOption) {\n this.tabActionOption = tabActionOption;\n }\n\n}" }, { "identifier": "CodeShellWidget", "path": "src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java", "snippet": "public class CodeShellWidget extends EditorBasedWidget\n implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation,\n CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener {\n public static final String ID = \"CodeShellWidget\";\n\n public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>(\"CodeShell Code Suggestion\");\n public static final Key<Integer> SHELL_CODER_POSITION = new Key<>(\"CodeShell Position\");\n public static boolean enableSuggestion = false;\n protected CodeShellWidget(@NotNull Project project) {\n super(project);\n }\n\n @Override\n public @NonNls @NotNull String ID() {\n return ID;\n }\n\n @Override\n public StatusBarWidget copy() {\n return new CodeShellWidget(getProject());\n }\n\n @Override\n public @Nullable Icon getIcon() {\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus());\n if (status == CodeShellStatus.OK) {\n return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled;\n } else {\n return CodeShellIcons.WidgetError;\n }\n }\n\n @Override\n public WidgetPresentation getPresentation() {\n return this;\n }\n\n @Override\n public @Nullable @NlsContexts.Tooltip String getTooltipText() {\n StringBuilder toolTipText = new StringBuilder(\"CodeShell\");\n if (CodeShellSettings.getInstance().isSaytEnabled()) {\n toolTipText.append(\" enabled\");\n } else {\n toolTipText.append(\" disabled\");\n }\n\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n int statusCode = codeShell.getStatus();\n CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode);\n switch (status) {\n case OK:\n if (CodeShellSettings.getInstance().isSaytEnabled()) {\n toolTipText.append(\" (Click to disable)\");\n } else {\n toolTipText.append(\" (Click to enable)\");\n }\n break;\n case UNKNOWN:\n toolTipText.append(\" (http error \");\n toolTipText.append(statusCode);\n toolTipText.append(\")\");\n break;\n default:\n toolTipText.append(\" (\");\n toolTipText.append(status.getDisplayValue());\n toolTipText.append(\")\");\n }\n\n return toolTipText.toString();\n }\n\n @Override\n public @Nullable Consumer<MouseEvent> getClickConsumer() {\n return mouseEvent -> {\n CodeShellSettings.getInstance().toggleSaytEnabled();\n if (Objects.nonNull(myStatusBar)) {\n myStatusBar.updateWidget(ID);\n }\n };\n }\n\n @Override\n public void install(@NotNull StatusBar statusBar) {\n super.install(statusBar);\n EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster();\n multicaster.addCaretListener(this, this);\n multicaster.addSelectionListener(this, this);\n multicaster.addDocumentListener(this, this);\n KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(\"focusOwner\", this);\n Disposer.register(this,\n () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener(\"focusOwner\",\n this)\n );\n }\n\n private Editor getFocusOwnerEditor() {\n Component component = getFocusOwnerComponent();\n Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor();\n return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null;\n }\n\n private Component getFocusOwnerComponent() {\n Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();\n if (Objects.isNull(focusOwner)) {\n IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject());\n Window frame = focusManager.getLastFocusedIdeWindow();\n if (Objects.nonNull(frame)) {\n focusOwner = focusManager.getLastFocusedFor(frame);\n }\n }\n return focusOwner;\n }\n\n private boolean isFocusedEditor(Editor editor) {\n Component focusOwner = getFocusOwnerComponent();\n return focusOwner == editor.getContentComponent();\n }\n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n updateInlayHints(getFocusOwnerEditor());\n }\n\n @Override\n public void selectionChanged(SelectionEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretPositionChanged(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretAdded(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretRemoved(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void afterDocumentChange(@NotNull Document document) {\n enableSuggestion = true;\n if (ApplicationManager.getApplication().isDispatchThread()) {\n EditorFactory.getInstance().editors(document)\n .filter(this::isFocusedEditor)\n .findFirst()\n .ifPresent(this::updateInlayHints);\n }\n }\n\n private void updateInlayHints(Editor focusedEditor) {\n if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) {\n return;\n }\n VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument());\n if (Objects.isNull(file)) {\n return;\n }\n\n String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText();\n if (Objects.nonNull(selection) && !selection.isEmpty()) {\n String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);\n if (Objects.nonNull(existingHints) && existingHints.length > 0) {\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);\n file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset());\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n }\n return;\n }\n\n Integer codeShellPos = file.getUserData(SHELL_CODER_POSITION);\n int lastPosition = (Objects.isNull(codeShellPos)) ? 0 : codeShellPos;\n int currentPosition = focusedEditor.getCaretModel().getOffset();\n\n if (lastPosition == currentPosition) return;\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n if (currentPosition > lastPosition) {\n String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);\n if (Objects.nonNull(existingHints) && existingHints.length > 0) {\n String inlineHint = existingHints[0];\n String modifiedText = focusedEditor.getDocument().getCharsSequence().subSequence(lastPosition, currentPosition).toString();\n if (modifiedText.startsWith(\"\\n\")) {\n modifiedText = modifiedText.replace(\" \", \"\");\n }\n if (inlineHint.startsWith(modifiedText)) {\n inlineHint = inlineHint.substring(modifiedText.length());\n enableSuggestion = false;\n if (inlineHint.length() > 0) {\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.addInlineElement(currentPosition, true, new CodeGenHintRenderer(inlineHint));\n existingHints[0] = inlineHint;\n\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, existingHints);\n file.putUserData(SHELL_CODER_POSITION, currentPosition);\n return;\n } else if (existingHints.length > 1) {\n existingHints = Arrays.copyOfRange(existingHints, 1, existingHints.length);\n CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, existingHints);\n return;\n } else {\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);\n }\n }\n }\n }\n\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n\n file.putUserData(SHELL_CODER_POSITION, currentPosition);\n if(!enableSuggestion || currentPosition < lastPosition){\n enableSuggestion = false;\n return;\n }\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n CharSequence editorContents = focusedEditor.getDocument().getCharsSequence();\n CompletableFuture<String[]> future = CompletableFuture.supplyAsync(() -> codeShell.getCodeCompletionHints(editorContents, currentPosition));\n future.thenAccept(hintList -> CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, hintList));\n }\n\n}" } ]
import com.alibaba.fastjson2.JSONObject; import com.codeshell.intellij.constant.PrefixString; import com.codeshell.intellij.model.GenerateModel; import com.codeshell.intellij.settings.CodeShellSettings; import com.codeshell.intellij.widget.CodeShellWidget; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.Inlay; import com.intellij.openapi.editor.InlayModel; import com.intellij.openapi.vfs.VirtualFile; import org.apache.commons.lang3.StringUtils; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
4,573
package com.codeshell.intellij.utils; public class CodeShellUtils { public static String includePreText(String preText, String language, String text) { String sufText = "\n```" + language + "\n" + text + "\n```\n"; return String.format(preText, language, sufText); } public static int prefixHandle(int begin, int end) { if (end - begin > 3000) { return end - 3000; } else { return begin; } } public static int suffixHandle(int begin, int end) { if (end - begin > 256) { return begin + 256; } else { return end; } } public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){ JsonObject httpBody = new JsonObject(); httpBody.addProperty("input_prefix", prefix); httpBody.addProperty("input_suffix", suffix); httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); httpBody.addProperty("temperature", 0.2); httpBody.addProperty("repetition_penalty", 1.0); httpBody.addProperty("top_k", 10); httpBody.addProperty("top_p", 0.95); // httpBody.addProperty("prompt", PrefixString.REQUST_END_TAG + codeShellPrompt); // httpBody.addProperty("frequency_penalty", 1.2); // httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); // httpBody.addProperty("stream", false); // JsonArray stopArray = new JsonArray(); // stopArray.add("|<end>|"); // httpBody.add("stop", stopArray); return httpBody; } public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){ JsonObject httpBody = new JsonObject(); httpBody.addProperty("inputs", codeShellPrompt); JsonObject parameters = new JsonObject(); parameters.addProperty("max_new_tokens", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); httpBody.add("parameters", parameters); return httpBody; } public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){ String generatedText = ""; Matcher matcher = pattern.matcher(responseBody); StringBuilder contentBuilder = new StringBuilder(); while (matcher.find()) { String jsonString = matcher.group(1); JSONObject json = JSONObject.parseObject(jsonString); String content = json.getString("content"); if(StringUtils.equalsAny(content, "<|endoftext|>", "")){ continue; } contentBuilder.append(content); } return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, ""); } public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){ String generatedText = ""; Gson gson = new Gson();
package com.codeshell.intellij.utils; public class CodeShellUtils { public static String includePreText(String preText, String language, String text) { String sufText = "\n```" + language + "\n" + text + "\n```\n"; return String.format(preText, language, sufText); } public static int prefixHandle(int begin, int end) { if (end - begin > 3000) { return end - 3000; } else { return begin; } } public static int suffixHandle(int begin, int end) { if (end - begin > 256) { return begin + 256; } else { return end; } } public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){ JsonObject httpBody = new JsonObject(); httpBody.addProperty("input_prefix", prefix); httpBody.addProperty("input_suffix", suffix); httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); httpBody.addProperty("temperature", 0.2); httpBody.addProperty("repetition_penalty", 1.0); httpBody.addProperty("top_k", 10); httpBody.addProperty("top_p", 0.95); // httpBody.addProperty("prompt", PrefixString.REQUST_END_TAG + codeShellPrompt); // httpBody.addProperty("frequency_penalty", 1.2); // httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); // httpBody.addProperty("stream", false); // JsonArray stopArray = new JsonArray(); // stopArray.add("|<end>|"); // httpBody.add("stop", stopArray); return httpBody; } public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){ JsonObject httpBody = new JsonObject(); httpBody.addProperty("inputs", codeShellPrompt); JsonObject parameters = new JsonObject(); parameters.addProperty("max_new_tokens", Integer.parseInt(settings.getCompletionMaxToken().getDescription())); httpBody.add("parameters", parameters); return httpBody; } public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){ String generatedText = ""; Matcher matcher = pattern.matcher(responseBody); StringBuilder contentBuilder = new StringBuilder(); while (matcher.find()) { String jsonString = matcher.group(1); JSONObject json = JSONObject.parseObject(jsonString); String content = json.getString("content"); if(StringUtils.equalsAny(content, "<|endoftext|>", "")){ continue; } contentBuilder.append(content); } return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, ""); } public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){ String generatedText = ""; Gson gson = new Gson();
GenerateModel generateModel = gson.fromJson(responseBody, GenerateModel.class);
1
2023-10-18 06:29:13+00:00
8k
djkcyl/Shamrock
qqinterface/src/main/java/tencent/im/oidb/cmd0x5eb/oidb_0x5eb.java
[ { "identifier": "ByteStringMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java", "snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr, int i2, int i3) {\n return null;\n }\n\n public static ByteStringMicro copyFromUtf8(String str) {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public int size() {\n return 0;\n }\n\n public byte[] toByteArray() {\n return null;\n }\n\n public String toString(String str) {\n return \"\";\n }\n\n public String toStringUtf8() {\n return \"\";\n }\n}" }, { "identifier": "MessageMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/MessageMicro.java", "snippet": "public class MessageMicro<T extends MessageMicro<T>> {\n public final T mergeFrom(byte[] bArr) {\n return null;\n }\n\n public final byte[] toByteArray() {\n return null;\n }\n\n public T get() {\n return null;\n }\n\n public void set(T t) {\n }\n}" }, { "identifier": "PBBytesField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBytesField.java", "snippet": "public class PBBytesField extends PBPrimitiveField<ByteStringMicro> {\n public static PBField<ByteStringMicro> __repeatHelper__;\n\n public PBBytesField(ByteStringMicro byteStringMicro, boolean z) {\n }\n\n public ByteStringMicro get() {\n return null;\n }\n\n public void set(ByteStringMicro byteStringMicro) {\n }\n}" }, { "identifier": "PBField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBField.java", "snippet": "public abstract class PBField<T> {\n public static <T extends MessageMicro<T>> PBRepeatMessageField<T> initRepeatMessage(Class<T> cls) {\n return new PBRepeatMessageField<>(cls);\n }\n\n public static <T> PBRepeatField<T> initRepeat(PBField<T> pBField) {\n return new PBRepeatField<>(pBField);\n }\n\n public static PBUInt32Field initUInt32(int i2) {\n return new PBUInt32Field(i2, false);\n }\n\n public static PBStringField initString(String str) {\n return new PBStringField(str, false);\n }\n\n public static PBBytesField initBytes(ByteStringMicro byteStringMicro) {\n return new PBBytesField(byteStringMicro, false);\n }\n\n public static PBBoolField initBool(boolean z) {\n return new PBBoolField(z, false);\n }\n\n public static PBInt32Field initInt32(int i2) {\n return new PBInt32Field(i2, false);\n }\n\n public static PBUInt64Field initUInt64(long j2) {\n return new PBUInt64Field(j2, false);\n }\n\n public static PBInt64Field initInt64(long j2) {\n return new PBInt64Field(j2, false);\n }\n\n public static PBEnumField initEnum(int i2) {\n return new PBEnumField(i2, false);\n }\n}" }, { "identifier": "PBStringField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBStringField.java", "snippet": "public class PBStringField extends PBPrimitiveField<String>{\n public PBStringField(String str, boolean z) {\n }\n\n public void set(String str, boolean z) {\n }\n\n public void set(String str) {\n }\n\n public String get() {\n return \"\";\n }\n}" }, { "identifier": "PBUInt32Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt32Field.java", "snippet": "public class PBUInt32Field extends PBPrimitiveField<Integer> {\n public static PBUInt32Field __repeatHelper__;\n\n public PBUInt32Field(int i2, boolean z) {\n }\n\n public void set(int i2) {\n\n }\n\n public int get() {\n return 0;\n }\n}" }, { "identifier": "PBUInt64Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt64Field.java", "snippet": "public class PBUInt64Field extends PBPrimitiveField<Long> {\n public static PBField<Long> __repeatHelper__;\n\n public PBUInt64Field(long i2, boolean z) {\n }\n\n public void set(long i2) {\n\n }\n\n public long get() {\n return 0;\n }\n}" } ]
import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBStringField; import com.tencent.mobileqq.pb.PBUInt32Field; import com.tencent.mobileqq.pb.PBUInt64Field;
4,143
public final PBUInt32Field uint32_flag_use_mobile_net_switch; public final PBUInt32Field uint32_flag_zplan_edit_avatar; public final PBUInt32Field uint32_forbid_flag; public final PBUInt32Field uint32_freshnews_notify_flag; public final PBUInt32Field uint32_gender; public final PBUInt32Field uint32_global_group_level; public final PBUInt32Field uint32_god_flag; public final PBUInt32Field uint32_god_forbid; public final PBUInt32Field uint32_group_mem_credit_flag; public final PBUInt32Field uint32_guild_gray_flag; public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin; public final PBUInt32Field uint32_hidden_session_switch; public final PBUInt32Field uint32_hidden_session_video_switch; public final PBUInt32Field uint32_input_status_flag; public final PBUInt32Field uint32_lang1; public final PBUInt32Field uint32_lang2; public final PBUInt32Field uint32_lang3; public final PBUInt32Field uint32_lflag; public final PBUInt32Field uint32_lightalk_switch; public final PBUInt32Field uint32_love_status; public final PBUInt32Field uint32_mss_update_time; public final PBUInt32Field uint32_music_ring_autoplay; public final PBUInt32Field uint32_music_ring_redpoint; public final PBUInt32Field uint32_music_ring_visible; public final PBUInt32Field uint32_normal_night_mode_flag; public final PBUInt32Field uint32_notify_on_like_ranking_list_flag; public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag; public final PBUInt32Field uint32_oin; public final PBUInt32Field uint32_online_status_avatar_switch; public final PBUInt32Field uint32_plate_of_king_dan; public final PBUInt32Field uint32_plate_of_king_dan_display_switch; public final PBUInt32Field uint32_posterfont_id; public final PBUInt32Field uint32_preload_disable_flag; public final PBUInt32Field uint32_profession; public final PBUInt32Field uint32_profile_age_visible; public final PBUInt32Field uint32_profile_anonymous_answer_switch; public final PBUInt32Field uint32_profile_birthday_visible; public final PBUInt32Field uint32_profile_college_visible; public final PBUInt32Field uint32_profile_company_visible; public final PBUInt32Field uint32_profile_constellation_visible; public final PBUInt32Field uint32_profile_dressup_switch; public final PBUInt32Field uint32_profile_email_visible; public final PBUInt32Field uint32_profile_hometown_visible; public final PBUInt32Field uint32_profile_interest_switch; public final PBUInt32Field uint32_profile_life_achievement_switch; public final PBUInt32Field uint32_profile_location_visible; public final PBUInt32Field uint32_profile_membership_and_rank; public final PBUInt32Field uint32_profile_miniapp_switch; public final PBUInt32Field uint32_profile_music_switch; public final PBUInt32Field uint32_profile_musicbox_switch; public final PBUInt32Field uint32_profile_personal_note_visible; public final PBUInt32Field uint32_profile_personality_label_switch; public final PBUInt32Field uint32_profile_present_switch; public final PBUInt32Field uint32_profile_privilege; public final PBUInt32Field uint32_profile_profession_visible; public final PBUInt32Field uint32_profile_qqcard_switch; public final PBUInt32Field uint32_profile_qqcircle_switch; public final PBUInt32Field uint32_profile_sex_visible; public final PBUInt32Field uint32_profile_show_idol_switch; public final PBUInt32Field uint32_profile_splendid_switch; public final PBUInt32Field uint32_profile_sticky_note_offline; public final PBUInt32Field uint32_profile_sticky_note_switch; public final PBUInt32Field uint32_profile_weishi_switch; public final PBUInt32Field uint32_profile_wz_game_card_switch; public final PBUInt32Field uint32_profile_wz_game_skin_switch; public final PBUInt32Field uint32_pstn_c2c_call_time; public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_c2c_try_flag; public final PBUInt32Field uint32_pstn_c2c_vip; public final PBUInt32Field uint32_pstn_ever_c2c_vip; public final PBUInt32Field uint32_pstn_ever_multi_vip; public final PBUInt32Field uint32_pstn_multi_call_time; public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_multi_try_flag; public final PBUInt32Field uint32_pstn_multi_vip; public final PBUInt32Field uint32_qq_assistant_switch; public final PBUInt32Field uint32_req_font_effect_id; public final PBUInt32Field uint32_req_global_ring_id; public final PBUInt32Field uint32_req_invite2group_auto_agree_flag; public final PBUInt32Field uint32_req_medalwall_flag; public final PBUInt32Field uint32_req_push_notice_flag; public final PBUInt32Field uint32_req_small_world_head_flag; public final PBUInt32Field uint32_rsp_connections_switch_id; public final PBUInt32Field uint32_rsp_listen_together_player_id; public final PBUInt32Field uint32_rsp_qq_level_icon_type; public final PBUInt32Field uint32_rsp_theme_font_id; public final PBUInt32Field uint32_school_status_flag; public final PBUInt32Field uint32_simple_ui_pref; public final PBUInt32Field uint32_simple_ui_switch; public final PBUInt32Field uint32_simple_update_time; public final PBUInt32Field uint32_stranger_vote_switch; public final PBUInt32Field uint32_subaccount_display_third_qq_flag; public final PBUInt32Field uint32_subscribe_nearbyassistant_switch; public final PBUInt32Field uint32_suspend_effect_id; public final PBUInt32Field uint32_sync_C2C_message_switch; public final PBUInt32Field uint32_torch_disable_flag; public final PBUInt32Field uint32_torchbearer_flag; public final PBUInt32Field uint32_troop_honor_rich_flag; public final PBUInt32Field uint32_troop_lucky_character_switch; public final PBUInt32Field uint32_troophonor_switch; public final PBUInt32Field uint32_vas_colorring_id; public final PBUInt32Field uint32_vas_diy_font_timestamp; public final PBUInt32Field uint32_vas_emoticon_usage_info; public final PBUInt32Field uint32_vas_face_id; public final PBUInt32Field uint32_vas_font_id; public final PBUInt32Field uint32_vas_magicfont_flag; public final PBUInt32Field uint32_vas_pendant_diy_id; public final PBUInt32Field uint32_vas_praise_id; public final PBUInt32Field uint32_vas_voicebubble_id; public final PBUInt32Field uint32_vip_flag; public final PBUInt32Field uint32_zplan_add_frd; public final PBUInt32Field uint32_zplan_cmshow_month_active_user; public final PBUInt32Field uint32_zplan_master_show; public final PBUInt32Field uint32_zplan_message_notice_switch; public final PBUInt32Field uint32_zplan_open; public final PBUInt32Field uint32_zplan_operators_network_switch; public final PBUInt32Field uint32_zplan_profile_card_show; public final PBUInt32Field uint32_zplan_qzone_show; public final PBUInt32Field uint32_zplan_samestyle_asset_switch; public final PBUInt32Field uint32_zplan_samestyle_package_switch;
package tencent.im.oidb.cmd0x5eb; public class oidb_0x5eb { public static final class UdcUinData extends MessageMicro<UdcUinData> { public final PBBytesField bytes_basic_cli_flag; public final PBBytesField bytes_basic_svr_flag; public final PBBytesField bytes_birthday; public final PBBytesField bytes_city; public final PBBytesField bytes_city_id; public final PBBytesField bytes_country; public final PBBytesField bytes_full_age; public final PBBytesField bytes_full_birthday; public final PBBytesField bytes_mss1_service; public final PBBytesField bytes_mss2_identity; public final PBBytesField bytes_mss3_bitmapextra; public final PBBytesField bytes_music_gene; public final PBBytesField bytes_nick; public final PBBytesField bytes_openid; public final PBBytesField bytes_province; public final PBBytesField bytes_req_vip_ext_id; public final PBBytesField bytes_stranger_declare; public final PBBytesField bytes_stranger_nick; public final PBUInt32Field int32_history_num_flag; public final PBUInt32Field roam_flag_qq_7day; public final PBUInt32Field roam_flag_svip_2year; public final PBUInt32Field roam_flag_svip_5year; public final PBUInt32Field roam_flag_svip_forever; public final PBUInt32Field roam_flag_vip_30day; public final PBStringField str_zplanphoto_url; public final PBUInt32Field uint32_400_flag; public final PBUInt32Field uint32_age; public final PBUInt32Field uint32_allow; public final PBUInt32Field uint32_alphabetic_font_flag; public final PBUInt32Field uint32_apollo_status; public final PBUInt32Field uint32_apollo_timestamp; public final PBUInt32Field uint32_apollo_vip_flag; public final PBUInt32Field uint32_apollo_vip_level; public final PBUInt32Field uint32_auth_flag; public final PBUInt32Field uint32_auto_to_text_flag; public final PBUInt32Field uint32_bubble_id; public final PBUInt32Field uint32_bubble_unread_switch; public final PBUInt32Field uint32_business_user; public final PBUInt32Field uint32_c2c_aio_shortcut_switch; public final PBUInt32Field uint32_charm; public final PBUInt32Field uint32_charm_level; public final PBUInt32Field uint32_charm_shown; public final PBUInt32Field uint32_city_zone_id; public final PBUInt32Field uint32_cmshow_3d_flag; public final PBUInt32Field uint32_common_place1; public final PBUInt32Field uint32_constellation; public final PBUInt32Field uint32_dance_max_score; public final PBUInt32Field uint32_default_cover_in_use; public final PBUInt32Field uint32_do_not_disturb_mode_time; public final PBUInt32Field uint32_elder_mode_flag; public final PBUInt32Field uint32_ext_flag; public final PBUInt32Field uint32_extend_friend_card_shown; public final PBUInt32Field uint32_extend_friend_flag; public final PBUInt32Field uint32_extend_friend_switch; public final PBUInt32Field uint32_face_id; public final PBUInt32Field uint32_file_assist_top; public final PBUInt32Field uint32_flag_color_note_recent_switch; public final PBUInt32Field uint32_flag_hide_pretty_group_owner_identity; public final PBUInt32Field uint32_flag_is_pretty_group_owner; public final PBUInt32Field uint32_flag_kid_mode_can_pull_group; public final PBUInt32Field uint32_flag_kid_mode_can_search_by_strangers; public final PBUInt32Field uint32_flag_kid_mode_can_search_friends; public final PBUInt32Field uint32_flag_kid_mode_need_phone_verify; public final PBUInt32Field uint32_flag_kid_mode_switch; public final PBUInt32Field uint32_flag_qcircle_cover_switch; public final PBUInt32Field uint32_flag_school_verified; public final PBUInt32Field uint32_flag_study_mode_student; public final PBUInt32Field uint32_flag_study_mode_switch; public final PBUInt32Field uint32_flag_super_yellow_diamond; public final PBUInt32Field uint32_flag_use_mobile_net_switch; public final PBUInt32Field uint32_flag_zplan_edit_avatar; public final PBUInt32Field uint32_forbid_flag; public final PBUInt32Field uint32_freshnews_notify_flag; public final PBUInt32Field uint32_gender; public final PBUInt32Field uint32_global_group_level; public final PBUInt32Field uint32_god_flag; public final PBUInt32Field uint32_god_forbid; public final PBUInt32Field uint32_group_mem_credit_flag; public final PBUInt32Field uint32_guild_gray_flag; public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin; public final PBUInt32Field uint32_hidden_session_switch; public final PBUInt32Field uint32_hidden_session_video_switch; public final PBUInt32Field uint32_input_status_flag; public final PBUInt32Field uint32_lang1; public final PBUInt32Field uint32_lang2; public final PBUInt32Field uint32_lang3; public final PBUInt32Field uint32_lflag; public final PBUInt32Field uint32_lightalk_switch; public final PBUInt32Field uint32_love_status; public final PBUInt32Field uint32_mss_update_time; public final PBUInt32Field uint32_music_ring_autoplay; public final PBUInt32Field uint32_music_ring_redpoint; public final PBUInt32Field uint32_music_ring_visible; public final PBUInt32Field uint32_normal_night_mode_flag; public final PBUInt32Field uint32_notify_on_like_ranking_list_flag; public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag; public final PBUInt32Field uint32_oin; public final PBUInt32Field uint32_online_status_avatar_switch; public final PBUInt32Field uint32_plate_of_king_dan; public final PBUInt32Field uint32_plate_of_king_dan_display_switch; public final PBUInt32Field uint32_posterfont_id; public final PBUInt32Field uint32_preload_disable_flag; public final PBUInt32Field uint32_profession; public final PBUInt32Field uint32_profile_age_visible; public final PBUInt32Field uint32_profile_anonymous_answer_switch; public final PBUInt32Field uint32_profile_birthday_visible; public final PBUInt32Field uint32_profile_college_visible; public final PBUInt32Field uint32_profile_company_visible; public final PBUInt32Field uint32_profile_constellation_visible; public final PBUInt32Field uint32_profile_dressup_switch; public final PBUInt32Field uint32_profile_email_visible; public final PBUInt32Field uint32_profile_hometown_visible; public final PBUInt32Field uint32_profile_interest_switch; public final PBUInt32Field uint32_profile_life_achievement_switch; public final PBUInt32Field uint32_profile_location_visible; public final PBUInt32Field uint32_profile_membership_and_rank; public final PBUInt32Field uint32_profile_miniapp_switch; public final PBUInt32Field uint32_profile_music_switch; public final PBUInt32Field uint32_profile_musicbox_switch; public final PBUInt32Field uint32_profile_personal_note_visible; public final PBUInt32Field uint32_profile_personality_label_switch; public final PBUInt32Field uint32_profile_present_switch; public final PBUInt32Field uint32_profile_privilege; public final PBUInt32Field uint32_profile_profession_visible; public final PBUInt32Field uint32_profile_qqcard_switch; public final PBUInt32Field uint32_profile_qqcircle_switch; public final PBUInt32Field uint32_profile_sex_visible; public final PBUInt32Field uint32_profile_show_idol_switch; public final PBUInt32Field uint32_profile_splendid_switch; public final PBUInt32Field uint32_profile_sticky_note_offline; public final PBUInt32Field uint32_profile_sticky_note_switch; public final PBUInt32Field uint32_profile_weishi_switch; public final PBUInt32Field uint32_profile_wz_game_card_switch; public final PBUInt32Field uint32_profile_wz_game_skin_switch; public final PBUInt32Field uint32_pstn_c2c_call_time; public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_c2c_try_flag; public final PBUInt32Field uint32_pstn_c2c_vip; public final PBUInt32Field uint32_pstn_ever_c2c_vip; public final PBUInt32Field uint32_pstn_ever_multi_vip; public final PBUInt32Field uint32_pstn_multi_call_time; public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_multi_try_flag; public final PBUInt32Field uint32_pstn_multi_vip; public final PBUInt32Field uint32_qq_assistant_switch; public final PBUInt32Field uint32_req_font_effect_id; public final PBUInt32Field uint32_req_global_ring_id; public final PBUInt32Field uint32_req_invite2group_auto_agree_flag; public final PBUInt32Field uint32_req_medalwall_flag; public final PBUInt32Field uint32_req_push_notice_flag; public final PBUInt32Field uint32_req_small_world_head_flag; public final PBUInt32Field uint32_rsp_connections_switch_id; public final PBUInt32Field uint32_rsp_listen_together_player_id; public final PBUInt32Field uint32_rsp_qq_level_icon_type; public final PBUInt32Field uint32_rsp_theme_font_id; public final PBUInt32Field uint32_school_status_flag; public final PBUInt32Field uint32_simple_ui_pref; public final PBUInt32Field uint32_simple_ui_switch; public final PBUInt32Field uint32_simple_update_time; public final PBUInt32Field uint32_stranger_vote_switch; public final PBUInt32Field uint32_subaccount_display_third_qq_flag; public final PBUInt32Field uint32_subscribe_nearbyassistant_switch; public final PBUInt32Field uint32_suspend_effect_id; public final PBUInt32Field uint32_sync_C2C_message_switch; public final PBUInt32Field uint32_torch_disable_flag; public final PBUInt32Field uint32_torchbearer_flag; public final PBUInt32Field uint32_troop_honor_rich_flag; public final PBUInt32Field uint32_troop_lucky_character_switch; public final PBUInt32Field uint32_troophonor_switch; public final PBUInt32Field uint32_vas_colorring_id; public final PBUInt32Field uint32_vas_diy_font_timestamp; public final PBUInt32Field uint32_vas_emoticon_usage_info; public final PBUInt32Field uint32_vas_face_id; public final PBUInt32Field uint32_vas_font_id; public final PBUInt32Field uint32_vas_magicfont_flag; public final PBUInt32Field uint32_vas_pendant_diy_id; public final PBUInt32Field uint32_vas_praise_id; public final PBUInt32Field uint32_vas_voicebubble_id; public final PBUInt32Field uint32_vip_flag; public final PBUInt32Field uint32_zplan_add_frd; public final PBUInt32Field uint32_zplan_cmshow_month_active_user; public final PBUInt32Field uint32_zplan_master_show; public final PBUInt32Field uint32_zplan_message_notice_switch; public final PBUInt32Field uint32_zplan_open; public final PBUInt32Field uint32_zplan_operators_network_switch; public final PBUInt32Field uint32_zplan_profile_card_show; public final PBUInt32Field uint32_zplan_qzone_show; public final PBUInt32Field uint32_zplan_samestyle_asset_switch; public final PBUInt32Field uint32_zplan_samestyle_package_switch;
public final PBUInt64Field uint64_face_addon_id;
6
2023-10-20 10:43:47+00:00
8k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/system/service/impl/SysMenuServiceImpl.java
[ { "identifier": "EuServiceImpl", "path": "eu-common-core/src/main/java/cn/eu/common/base/service/impl/EuServiceImpl.java", "snippet": "public abstract class EuServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IEuService<T> {\n\n /**\n * 分页参数从1开始\n */\n protected void getPage(Pageable pageable) {\n getPage(pageable, true);\n }\n\n /**\n * 分页参数从1开始\n */\n protected void getPage(Pageable pageable, boolean isOrder) {\n if (isOrder) {\n String order = null;\n if (pageable.getSort() != null) {\n order = pageable.getSort().toString();\n order = order.replace(\":\", \" \");\n if (\"UNSORTED\".equals(order)) {\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());\n return;\n }\n }\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize(), order);\n } else {\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());\n }\n }\n}" }, { "identifier": "MenuStatus", "path": "eu-common-core/src/main/java/cn/eu/common/enums/MenuStatus.java", "snippet": "@Getter\npublic enum MenuStatus {\n\n /**\n * 正常\n */\n NORMAL(0),\n\n /**\n * 禁用\n */\n DISABLE(1);\n\n private int value;\n\n MenuStatus(int value) {\n this.value = value;\n }\n}" }, { "identifier": "MenuType", "path": "eu-common-core/src/main/java/cn/eu/common/enums/MenuType.java", "snippet": "@Getter\npublic enum MenuType {\n\n /**\n * 目录\n */\n CATALOG(1),\n\n /**\n * 菜单\n */\n MENU(2),\n\n /**\n * 按钮\n */\n BUTTON(3);\n\n private int value;\n\n MenuType(int value) {\n this.value = value;\n }\n}" }, { "identifier": "PageResult", "path": "eu-common-core/src/main/java/cn/eu/common/model/PageResult.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PageResult<T> {\n\n private List<T> records;\n private Long total;\n\n public static <T> PageResult<T> of(List<T> records, Long total) {\n return new PageResult<>(records, total);\n }\n\n public static <T> PageResult<T> of(List<T> records) {\n PageInfo<T> pageInfo = new PageInfo<>(records);\n return of(pageInfo.getList(), pageInfo.getTotal());\n }\n\n}" }, { "identifier": "MpQueryHelper", "path": "eu-common-core/src/main/java/cn/eu/common/utils/MpQueryHelper.java", "snippet": "@Slf4j\npublic class MpQueryHelper {\n\n /**\n * 不校验值为空的查询类型\n */\n private static final List<Query.Type> NOT_NONNULL_QUERY_TYPE = Arrays.asList(\n Query.Type.IS_NULL,\n Query.Type.IS_NOT_NULL\n );\n\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapper(Object criteria, Class<T> entity) {\n return buildQueryWrapper(criteria, entity, null);\n }\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @param tableAlias 表别名\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapper(Object criteria, Class<T> entity, String tableAlias) {\n QueryWrapper<T> queryWrapper = new QueryWrapper<>();\n if (criteria == null) {\n return queryWrapper;\n }\n\n try {\n // 获取criteria(包括父类)的所有字段\n List<Field> fields = getAllFields(criteria);\n\n // 遍历所有的字段,并根据@Query注解填充QueryWrapper查询条件\n for (Field field : fields) {\n boolean accessible = field.isAccessible();\n // 设置可访问\n field.setAccessible(true);\n Query annotation = field.getAnnotation(Query.class);\n if (annotation != null) {\n Object value = field.get(criteria);\n Query.Type queryType = annotation.type();\n\n // 判断值是否为空\n boolean isNonNull = value != null && !(value instanceof String && StrUtil.isBlank((String) value));\n\n // 判断查询类型是否不需要校验空值\n boolean isNotNonNull = NOT_NONNULL_QUERY_TYPE.contains(queryType);\n\n if (isNotNonNull || isNonNull) {\n String fieldName = field.getName();\n\n // 设置查询条件\n fillQueryWrapper(queryWrapper, queryType, value, fieldName, tableAlias);\n }\n }\n // 恢复可访问设置\n field.setAccessible(accessible);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n\n return queryWrapper;\n }\n\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper,并在最后附件上逻辑删除的查询条件\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @param tableAlias 表别名\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapperWithDelFlag(Object criteria, Class<T> entity, String tableAlias) {\n QueryWrapper<T> queryWrapper = buildQueryWrapper(criteria, entity, tableAlias);\n // 如果在Mapper里使用${ew.customSqlSegment}这样方式拼接查询条件,@TableLogic不会生效所以需要手动添加\n queryWrapper.eq(wrapperAliasField(tableAlias, StrUtil.toUnderlineCase(Constants.DEL_FLAG_FIELD_NAME)), Constants.DEL_FLAG_NORMAL);\n return queryWrapper;\n }\n\n /**\n * 根据字段上Query.Type的类型,为QueryWrapper设置查询条件\n * @param queryWrapper QueryWrapper\n * @param queryType Query.Type\n * @param value 查询值\n * @param attributeName 查询字段名\n * @param tableAlias 表别名\n * @param <T> 实体类\n */\n private static <T> void fillQueryWrapper(QueryWrapper<T> queryWrapper, Query.Type queryType, Object value, String attributeName, String tableAlias) {\n String fieldName = StrUtil.toUnderlineCase(attributeName);\n fieldName = wrapperAliasField(tableAlias, fieldName);\n switch (queryType) {\n case EQ:\n queryWrapper.eq(fieldName, value);\n break;\n case GT:\n queryWrapper.gt(fieldName, value);\n break;\n case GE:\n queryWrapper.ge(fieldName, value);\n break;\n case LT:\n queryWrapper.lt(fieldName, value);\n break;\n case LE:\n queryWrapper.le(fieldName, value);\n break;\n case NE:\n queryWrapper.ne(fieldName, value);\n break;\n case LIKE:\n queryWrapper.like(fieldName, value);\n break;\n case LEFT_LIKE:\n queryWrapper.likeLeft(fieldName, value);\n break;\n case RIGHT_LIKE:\n queryWrapper.likeRight(fieldName, value);\n break;\n case IN:\n if (value instanceof Collection) {\n queryWrapper.in(fieldName, (Collection<?>) value);\n } else {\n queryWrapper.in(fieldName, value);\n }\n break;\n case NOT_IN:\n if (value instanceof Collection) {\n queryWrapper.notIn(fieldName, (Collection<?>) value);\n } else {\n queryWrapper.notIn(fieldName, value);\n }\n break;\n case IS_NULL:\n queryWrapper.isNull(fieldName);\n break;\n case IS_NOT_NULL:\n queryWrapper.isNotNull(fieldName);\n break;\n case BETWEEN:\n if (value instanceof Collection) {\n // 取出第一个和第二个值,如果不是两个值,就不处理,如果是两个值,并且不为空,就处理\n Object[] values = ((Collection<?>) value).toArray();\n if (ArrayUtil.isNotEmpty(values)) {\n if (values.length == 2 && values[0] != null && values[1] != null) {\n queryWrapper.between(fieldName, values[0], values[1]);\n } else {\n log.warn(\"BETWEEN条件需要两个值,当前值为:{}\", value);\n }\n }\n }\n break;\n default:\n // nothing\n log.warn(\"未支持的查询类型:{}\", queryType.name());\n break;\n }\n }\n\n private static String wrapperAliasField(String tableAlias, String fieldName) {\n if (StrUtil.isNotBlank(tableAlias)) {\n return tableAlias + \".\" + fieldName;\n }\n return fieldName;\n }\n\n /**\n * 获取对象的所有字段,包括父类的字段\n * @param entity 要获取字段的对象\n * @return List<Field> 该对象的所有字段\n */\n private static List<Field> getAllFields(Object entity) {\n List<Field> fields = new ArrayList<>();\n Class<?> clazz = entity.getClass();\n while (clazz != null) {\n fields.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n return fields;\n }\n\n}" }, { "identifier": "SecurityUtil", "path": "eu-admin/src/main/java/cn/eu/security/SecurityUtil.java", "snippet": "@Slf4j\npublic class SecurityUtil {\n\n /**\n * 当前登录用户是否为管理员\n */\n public static boolean isAdminLogin() {\n Object extra = StpUtil.getSession().get(Constants.IS_ADMIN_KEY);\n return extra != null && StrUtil.equals(extra.toString(), \"1\");\n }\n\n /**\n * 获取当前登录用户\n */\n public static AuthUser getLoginUser() {\n Object userStr = StpUtil.getSession().get(Constants.USER_KEY);\n Objects.requireNonNull(userStr);\n return JSONObject.parseObject(userStr.toString(), AuthUser.class);\n }\n\n /**\n * 从SaSession中提取登录用户数据\n * @param session SaSession\n * @return AuthUser\n */\n public static AuthUser getLoginUserBySaSession(SaSession session) {\n Object userStr = session.get(Constants.USER_KEY);\n Objects.requireNonNull(userStr);\n return JSONObject.parseObject(userStr.toString(), AuthUser.class);\n }\n\n /**\n * 设置当前登录用户\n */\n public static void setLoginUser(AuthUser authUser) {\n StpUtil.getSession().set(Constants.USER_KEY, authUser);\n }\n\n /**\n * 设置当前登录用户是否为管理员\n */\n public static void setLoginUserIsAdmin(Integer admin) {\n StpUtil.getSession().set(Constants.IS_ADMIN_KEY, admin);\n }\n\n /**\n * 设置当前登录用户拥有的角色\n */\n public static void setLoginUserRoles(List<SysRole> roles) {\n if (CollUtil.isEmpty(roles)) {\n return;\n }\n StpUtil.getSession().set(Constants.ROLE_KEY, roles);\n }\n\n public static List<SysRole> getLoginUserRoles() {\n Object roles = StpUtil.getSession().get(Constants.ROLE_KEY);\n List<SysRole> roleList = new ArrayList<>();\n try {\n roleList = Optional.ofNullable(JSONObject.parseArray(roles.toString(), SysRole.class))\n .orElse(new ArrayList<>());\n } catch (Exception e) {\n log.error(\"getLoginUserRoles error\", e);\n }\n return roleList;\n }\n\n /**\n * 根据SysUser填充AuthUser\n */\n public static AuthUser fillAuthUserBySysUser(AuthUser authUser, SysUser sysUser) {\n if (StrUtil.isNotBlank(sysUser.getId())) {\n authUser.setUserId(sysUser.getId());\n }\n if (StrUtil.isNotBlank(sysUser.getUsername())) {\n authUser.setUsername(sysUser.getUsername());\n }\n if (StrUtil.isNotBlank(sysUser.getNickname())) {\n authUser.setNickname(sysUser.getNickname());\n }\n if (StrUtil.isNotBlank(sysUser.getAvatar())) {\n authUser.setAvatar(sysUser.getAvatar());\n }\n if (StrUtil.isNotBlank(sysUser.getMobile())) {\n authUser.setMobile(sysUser.getMobile());\n }\n if (StrUtil.isNotBlank(sysUser.getEmail())) {\n authUser.setEmail(sysUser.getEmail());\n }\n if (sysUser.getSex() != null) {\n authUser.setSex(sysUser.getSex());\n }\n if (sysUser.getAdmin() != null) {\n authUser.setAdmin(sysUser.getAdmin());\n }\n if (sysUser.getDeptId() != null) {\n authUser.setDeptId(sysUser.getDeptId());\n }\n return authUser;\n }\n}" }, { "identifier": "SysMenu", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysMenu.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_menu\")\npublic class SysMenu extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n /** 菜单名称 */\n private String menuName;\n /** 菜单图标 */\n private String menuIcon;\n /** 显示顺序 */\n private Integer sortNum;\n /** 权限标识 */\n private String permission;\n /** 路由地址 */\n private String path;\n /** 组件名称 */\n private String componentName;\n /** 组件路径 */\n private String component;\n /**\n * 菜单状态\n * @see MenuStatus#getValue()\n */\n private Integer status;\n /** 是否固定 */\n private Boolean affix;\n /** 是否显示 */\n private Boolean visible;\n /** 是否缓存 */\n @TableField(\"`cache`\")\n private Boolean cache;\n /** 是否内嵌 */\n private Boolean embed;\n private String embedUrl;\n /** 是否显示小红点 */\n private Boolean dot;\n /** 徽标内容 */\n private String badge;\n /**\n * 菜单类型\n * @see MenuType#getValue()\n */\n private Integer menuType;\n /** 父菜单ID */\n private Integer parentId;\n /** 是否显示Header */\n private Boolean showHeader;\n /** 是否显示Footer */\n private Boolean showFooter;\n /**\n * 是否在只有一个子菜单时保持显示\n * true: 保持显示\n * false: 隐藏该菜单并在该菜单的位置显示该菜单的子菜单\n */\n private Boolean alwaysShow;\n}" }, { "identifier": "SysMenuMapper", "path": "eu-admin/src/main/java/cn/eu/system/mapper/SysMenuMapper.java", "snippet": "@Mapper\npublic interface SysMenuMapper extends EuBaseMapper<SysMenu> {\n List<SysMenu> getMenuPermissionByUserId(@Param(\"userId\") String userId, @Param(\"status\") Integer status);\n\n List<SysMenu> getMenusByUserId(@Param(\"userId\") String userId, @Param(\"status\") Integer status, @Param(\"menuType\") Integer menuType);\n\n List<SysMenu> selectMenus(@Param(Constants.WRAPPER) Wrapper<SysMenu> wrapper, @Param(\"userId\") String userId);\n}" }, { "identifier": "SysMenuQueryCriteria", "path": "eu-admin/src/main/java/cn/eu/system/model/query/SysMenuQueryCriteria.java", "snippet": "@Data\npublic class SysMenuQueryCriteria {\n\n @Query(type = Query.Type.LIKE)\n private String menuName;\n @Query\n private Integer status;\n\n}" }, { "identifier": "ISysMenuService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysMenuService.java", "snippet": "public interface ISysMenuService extends IEuService<SysMenu> {\n\n List<SysMenu> list(SysMenuQueryCriteria criteria);\n\n /**\n * 获取用户拥有的菜单权限\n * @param userId\n * @return\n */\n List<String> getMenuPermissionByUserId(String userId);\n\n /**\n * 获取用户拥有的菜单(不包含按钮)\n * @param userId 用户id\n * @return 所拥有的菜单列表\n */\n List<SysMenu> getMenusByUserId(String userId);\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import cn.eu.common.base.service.impl.EuServiceImpl; import cn.eu.common.enums.MenuStatus; import cn.eu.common.enums.MenuType; import cn.eu.common.model.PageResult; import cn.eu.common.utils.MpQueryHelper; import cn.eu.security.SecurityUtil; import cn.eu.system.domain.SysMenu; import cn.eu.system.mapper.SysMenuMapper; import cn.eu.system.model.query.SysMenuQueryCriteria; import cn.eu.system.service.ISysMenuService; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors;
4,255
package cn.eu.system.service.impl; /** * @author zhaoeryu * @since 2023/5/31 */ @Service public class SysMenuServiceImpl extends EuServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService { @Autowired SysMenuMapper sysMenuMapper; @Override public List<SysMenu> list(SysMenuQueryCriteria criteria) {
package cn.eu.system.service.impl; /** * @author zhaoeryu * @since 2023/5/31 */ @Service public class SysMenuServiceImpl extends EuServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService { @Autowired SysMenuMapper sysMenuMapper; @Override public List<SysMenu> list(SysMenuQueryCriteria criteria) {
criteria.setStatus(MenuStatus.NORMAL.getValue());
1
2023-10-20 07:08:37+00:00
8k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/recipe/machineRecipe/CokingFactoryRecipePool.java
[ { "identifier": "copyAmount", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/Utils.java", "snippet": "public static ItemStack copyAmount(int aAmount, ItemStack aStack) {\n ItemStack rStack = aStack.copy();\n if (isStackInvalid(rStack)) return null;\n // if (aAmount > 64) aAmount = 64;\n else if (aAmount == -1) aAmount = 111;\n else if (aAmount < 0) aAmount = 0;\n rStack.stackSize = aAmount;\n return rStack;\n}" }, { "identifier": "RECIPE_MV", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/enums/TierEU.java", "snippet": "public static final long RECIPE_MV = VP[2];" }, { "identifier": "RECIPE_UV", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/enums/TierEU.java", "snippet": "public static final long RECIPE_UV = VP[8];" }, { "identifier": "GTCMRecipe", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/recipeMap/GTCMRecipe.java", "snippet": "public class GTCMRecipe {\n\n // public static final GTCMRecipe instance = new GTCMRecipe();\n\n // public static class GTCMRecipeMap extends GT_Recipe.GT_Recipe_Map {\n //\n // /**\n // * Initialises a new type of Recipe Handler.\n // *\n // * @param aRecipeList a List you specify as Recipe List. Usually just an ArrayList with a\n // * pre-initialised Size.\n // * @param aUnlocalizedName the unlocalised Name of this Recipe Handler, used mainly for NEI.\n // * @param aLocalName @deprecated the displayed Name of the NEI Recipe GUI title,\n // * if null then use the aUnlocalizedName;\n // * always is null, by using aUnlocalizedName with i18n.\n // * @param aNEIName\n // * @param aNEIGUIPath the displayed GUI Texture, usually just a Machine GUI. Auto-Attaches \".png\"\n // * if forgotten.\n // * @param aUsualInputCount the usual amount of Input Slots this Recipe Class has.\n // * @param aUsualOutputCount the usual amount of Output Slots this Recipe Class has.\n // * @param aUsualFluidInputCount the usual amount of Fluid Input Slots this Recipe Class has.\n // * @param aUsualFluidOutputCount the usual amount of Fluid Output Slots this Recipe Class has.\n // * @param aMinimalInputItems\n // * @param aMinimalInputFluids\n // * @param aAmperage\n // * @param aNEISpecialValuePre the String in front of the Special Value in NEI.\n // * @param aNEISpecialValueMultiplier the Value the Special Value is getting Multiplied with before displaying\n // * @param aNEISpecialValuePost the String after the Special Value. Usually for a Unit or something.\n // * @param aShowVoltageAmperageInNEI\n // * @param aNEIAllowed if NEI is allowed to display this Recipe Handler in general.\n // */\n // public GTCMRecipeMap(Collection<gregtech.api.util.GT_Recipe> aRecipeList, String aUnlocalizedName,\n // String aLocalName, String aNEIName, String aNEIGUIPath, int aUsualInputCount, int aUsualOutputCount,\n // int aUsualFluidInputCount, int aUsualFluidOutputCount, boolean disableOptimize, int aMinimalInputItems,\n // int aMinimalInputFluids, int aAmperage, String aNEISpecialValuePre, int aNEISpecialValueMultiplier,\n // String aNEISpecialValuePost, boolean aShowVoltageAmperageInNEI, boolean aNEIAllowed) {\n // super(\n // aRecipeList,\n // aUnlocalizedName,\n // aLocalName,\n // aNEIName,\n // aNEIGUIPath,\n // aUsualInputCount,\n // aUsualOutputCount,\n // aMinimalInputItems,\n // aMinimalInputFluids,\n // aAmperage,\n // aNEISpecialValuePre,\n // aNEISpecialValueMultiplier,\n // aNEISpecialValuePost,\n // aShowVoltageAmperageInNEI,\n // aNEIAllowed);\n //\n // useModularUI(true);\n // // setProgressBarPos(78, getItemRowCount() * 18);\n // setLogoPos(79, 7);\n // setUsualFluidInputCount(aUsualFluidInputCount);\n // setUsualFluidOutputCount(aUsualFluidOutputCount);\n // setDisableOptimize(disableOptimize);\n //\n // }\n //\n // private static final int xDirMaxCount = 4;\n // private static final int yOrigin = 8;\n //\n // private int getItemRowCount() {\n // return (Math.max(mUsualInputCount, mUsualOutputCount) - 1) / xDirMaxCount + 1;\n // }\n //\n // private int getFluidRowCount() {\n // return (Math.max(getUsualFluidInputCount(), getUsualFluidOutputCount()) - 1) / xDirMaxCount + 1;\n // }\n //\n // @Override\n // public List<Pos2d> getItemInputPositions(int itemInputCount) {\n // return UIHelper.getGridPositions(itemInputCount, 6, yOrigin, xDirMaxCount);\n // }\n //\n // @Override\n // public List<Pos2d> getItemOutputPositions(int itemOutputCount) {\n // return UIHelper.getGridPositions(itemOutputCount, 98, yOrigin, xDirMaxCount);\n // }\n //\n // @Override\n // public List<Pos2d> getFluidInputPositions(int fluidInputCount) {\n // return UIHelper.getGridPositions(fluidInputCount, 6, yOrigin + getItemRowCount() * 18, xDirMaxCount);\n // }\n //\n // @Override\n // public List<Pos2d> getFluidOutputPositions(int fluidOutputCount) {\n // return UIHelper.getGridPositions(fluidOutputCount, 98, yOrigin + getItemRowCount() * 18, xDirMaxCount);\n // }\n //\n // @Override\n // public ModularWindow.Builder createNEITemplate(IItemHandlerModifiable itemInputsInventory,\n // IItemHandlerModifiable itemOutputsInventory, IItemHandlerModifiable specialSlotInventory,\n // IItemHandlerModifiable fluidInputsInventory, IItemHandlerModifiable fluidOutputsInventory,\n // Supplier<Float> progressSupplier, Pos2d windowOffset) {\n // // Delay setter so that calls to #setUsualFluidInputCount and #setUsualFluidOutputCount are considered\n // setNEIBackgroundSize(172, 10 + (getItemRowCount() + getFluidRowCount()) * 18);\n // // setNEIBackgroundSize(172, 82 + (Math.max(getItemRowCount() + getFluidRowCount() - 4, 0)) * 18);\n // return super.createNEITemplate(\n // itemInputsInventory,\n // itemOutputsInventory,\n // specialSlotInventory,\n // fluidInputsInventory,\n // fluidOutputsInventory,\n // progressSupplier,\n // windowOffset);\n // }\n //\n // }\n\n public static final RecipeMap<TST_RecipeMapBackend> IntensifyChemicalDistorterRecipes = RecipeMapBuilder\n // At the same time , the localization key of the NEI Name\n // of this page.\n .of(\"gtcm.recipe.IntensifyChemicalDistorterRecipes\", TST_RecipeMapBackend::new)\n .maxIO(16, 16, 16, 16)\n .neiSpecialInfoFormatter(HeatingCoilSpecialValueFormatter.INSTANCE)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(\n builder -> builder.setDisplayStack(GTCMItemList.IntensifyChemicalDistorter.get(1))\n .setMaxRecipesPerPage(1))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap IntensifyChemicalDistorterRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.IntensifyChemicalDistorterRecipes\",\n // NameIntensifyChemicalDistorter,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 16,\n // 16,\n // 16,\n // 16,\n // true,\n // 0,\n // 0,\n // 1,\n // HeatCapacity,\n // 1,\n // Kelvin,\n // false,\n // true);\n\n public static final RecipeMap<TST_RecipeMapBackend> PreciseHighEnergyPhotonicQuantumMasterRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.PreciseHighEnergyPhotonicQuantumMasterRecipes\", TST_RecipeMapBackend::new)\n .maxIO(16, 16, 16, 16)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(\n builder -> builder.setDisplayStack(GTCMItemList.PreciseHighEnergyPhotonicQuantumMaster.get(1))\n .setMaxRecipesPerPage(1))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap PreciseHighEnergyPhotonicQuantumMasterRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.PreciseHighEnergyPhotonicQuantumMasterRecipes\",\n // NamePreciseHighEnergyPhotonicQuantumMaster,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 16,\n // 16,\n // 16,\n // 16,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<TST_RecipeMapBackend> MiracleTopRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.MiracleTopRecipes\", TST_RecipeMapBackend::new)\n .maxIO(16, 16, 16, 4)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(\n builder -> builder.setDisplayStack(GTCMItemList.MiracleTop.get(1))\n .setMaxRecipesPerPage(1))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap MiracleTopRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.MiracleTopRecipes\",\n // NameMiracleTop,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 16,\n // 16,\n // 16,\n // 4,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> QuantumInversionRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.QuantumInversionRecipes\")\n .maxIO(1, 1, 1, 1)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.MiracleTop.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap QuantumInversionRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.QuantumInversionRecipes\",\n // texter(\"Quantum Inversion\", \"NEI.QuantumInversion\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 4,\n // 4,\n // 4,\n // 4,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> CrystallineInfinitierRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.CrystallineInfinitierRecipes\")\n .maxIO(4, 4, 4, 1)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.CrystallineInfinitier.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap CrystallineInfinitierRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.CrystallineInfinitierRecipes\",\n // NameCrystallineInfinitier,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 4,\n // 4,\n // 4,\n // 1,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> DSP_LauncherRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.DSPLauncherRecipes\")\n .maxIO(1, 1, 1, 0)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap DSP_LauncherRecipes = new GTCMRecipeMap(\n // new HashSet<>(2),\n // \"gtcm.recipe.DSPLauncherRecipes\",\n // NameDSPLauncher,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 1,\n // 1,\n // 1,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> DSP_ReceiverRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.DSPReceiverRecipes\")\n .maxIO(0, 1, 0, 0)\n .neiSpecialInfoFormatter(DSP_Receiver_SpecialValueFormatter.INSTANCE)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.DSPReceiver.get(1)))\n .disableOptimize()\n .build();\n // public final GTCMRecipeMap DSP_ReceiverRecipes = new GTCMRecipeMap(\n // new HashSet<>(1),\n // \"gtcm.recipe.DSPReceiverRecipes\",\n // NameDSPReceiver,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 1,\n // 1,\n // 0,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // texter(\"Equivalence value of EU : \", \"NEI.DSP_ReceiverRecipes.specialValue.pre\"),\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> ElvenWorkshopRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.ElvenWorkshopRecipes\")\n .maxIO(4, 4, 1, 0)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.ElvenWorkshop.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap ElvenWorkshopRecipes = new GTCMRecipeMap(\n // new HashSet<>(1),\n // \"gtcm.recipe.ElvenWorkshopRecipes\",\n // texter(\"Mana Infusion\", \"NEI.name.ManaInfusion\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 4,\n // 1,\n // 1,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> RuneEngraverRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.RuneEngraverRecipes\")\n .maxIO(6, 1, 1, 0)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.ElvenWorkshop.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap RuneEngraverRecipes = new GTCMRecipeMap(\n // new HashSet<>(1),\n // \"gtcm.recipe.RuneEngraverRecipes\",\n // texter(\"Rune Engrave\", \"NEI.name.RuneEngrave\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 8,\n // 1,\n // 1,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> ArtificialStarGeneratingRecipes = RecipeMapBuilder\n .of(\"gtcm.recipe.ArtificialStarGeneratingRecipes\")\n .maxIO(1, 1, 0, 0)\n .neiSpecialInfoFormatter(ArtificialStar_SpecialValueFormatter.INSTANCE)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.ArtificialStar.get(1)))\n .disableOptimize()\n .build();\n // public final GTCMRecipeMap ArtificialStarGeneratingRecipes = new GTCMRecipeMap(\n // new HashSet<>(2),\n // \"gtcm.recipe.ArtificialStarGeneratingRecipes\",\n // NameArtificialStar,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 1,\n // 1,\n // 0,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // texter(\"Generate : \", \"NEI.ArtificialStarGeneratingRecipes.specialValue.pre\"),\n // 1,\n // \" × 2,147,483,647 EU\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> megaUniversalSpaceStationRecipePool = RecipeMapBuilder\n .of(\"gtcm.recipe.megaUniversalSpaceStationRecipePool\")\n .maxIO(16, 4, 16, 1)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.MiracleTop.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap megaUniversalSpaceStationRecipePool = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"gtcm.recipe.megaUniversalSpaceStationRecipes\",\n // NameMegaUniversalSpaceStation,\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 16,\n // 4,\n // 16,\n // 1,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // true,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> OreProcessingRecipes = RecipeMapBuilder\n .of(\"tst.recipe.OreProcessingRecipes\")\n .maxIO(1, 9, 1, 0)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.OreProcessingFactory.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap OreProcessingRecipes = new GTCMRecipeMap(\n // new HashSet<>(1000),\n // \"tst.recipe.OreProcessingRecipes\",\n // texter(\"Ore Processing Recipes\", \"NEI.name.OreProcessingRecipes\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 1,\n // 8,\n // 1,\n // 0,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> CokingFactoryRecipes = RecipeMapBuilder\n .of(\"tst.recipe.CokingFactoryRecipes\")\n .maxIO(2, 2, 1, 1)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap CokingFactoryRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"tst.recipe.CokingFactoryRecipes\",\n // texter(\"Coking Factory Recipes\", \"NEI.name.CokingFactoryRecipes\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 2,\n // 2,\n // 1,\n // 1,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> StellarForgeRecipes = RecipeMapBuilder\n .of(\"tst.recipe.StellarForgeRecipes\")\n .maxIO(4, 4, 1, 2)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.MiracleDoor.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap StellarForgeRecipes = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"tst.recipe.StellarForgeRecipes\",\n // texter(\"Stellar Forge\", \"NEI.name.StellarForgeRecipes\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 4,\n // 4,\n // 4,\n // 4,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> HyperSpacetimeTransformerRecipe = RecipeMapBuilder\n .of(\"tst.recipe.HyperSpacetimeTransformerRecipe\")\n .maxIO(4, 4, 4, 4)\n .progressBar(GT_UITextures.PROGRESSBAR_ARROW_MULTIPLE)\n .frontend(TST_GeneralFrontend::new)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.HyperSpacetimeTransformer.get(1)))\n .disableOptimize()\n .build();\n\n // public final GTCMRecipeMap HyperSpacetimeTransformerRecipe = new GTCMRecipeMap(\n // new HashSet<>(),\n // \"tst.recipe.HyperSpacetimeTransformerRecipe\",\n // texter(\"Hyper Spacetime Transformer\", \"NEI.name.HyperSpacetimeTransformerRecipe\"),\n // null,\n // \"gregtech:textures/gui/basicmachines/LCRNEI\",\n // 4,\n // 4,\n // 4,\n // 4,\n // true,\n // 0,\n // 0,\n // 1,\n // \"\",\n // 1,\n // \"\",\n // false,\n // true);\n\n public static final RecipeMap<RecipeMapBackend> AssemblyLineWithoutResearchRecipe = RecipeMapBuilder\n .of(\"tst.recipe.AssemblyLineWithoutResearchRecipe\")\n .maxIO(16, 1, 4, 0)\n .maxIO(16, 1, 4, 0)\n .minInputs(1, 0)\n .useSpecialSlot()\n // .slotOverlays((index, isFluid, isOutput, isSpecial) -> isSpecial ? GT_UITextures.OVERLAY_SLOT_DATA_ORB :\n // null)\n .disableOptimize()\n .neiTransferRect(88, 8, 18, 72)\n .neiTransferRect(124, 8, 18, 72)\n .neiTransferRect(142, 26, 18, 18)\n .neiHandlerInfo(builder -> builder.setDisplayStack(GTCMItemList.IndistinctTentacle.get(1)))\n .frontend(AssemblyLineFrontend::new)\n .build();\n\n // endregion\n}" }, { "identifier": "IRecipePool", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/recipe/IRecipePool.java", "snippet": "public interface IRecipePool {\n\n /**\n * Called at RecipeLoader\n */\n void loadRecipes();\n}" } ]
import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_MV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UV; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool; import com.dreammaster.gthandler.GT_CoreModSupport; import gregtech.api.enums.GT_Values; import gregtech.api.enums.Materials; import gregtech.api.interfaces.IRecipeMap; import gregtech.api.util.GT_ModHandler; import gregtech.api.util.GT_Utility;
6,593
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class CokingFactoryRecipePool implements IRecipePool { @Override public void loadRecipes() { final IRecipeMap coke = GTCMRecipe.CokingFactoryRecipes; // Raw Radox GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(24), GT_ModHandler.getModItem("GalaxySpace", "barnardaClog", 64)) .fluidInputs(GT_CoreModSupport.Xenoxene.getFluid(1000)) .fluidOutputs(GT_CoreModSupport.RawRadox.getFluid(1000 * 2))
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class CokingFactoryRecipePool implements IRecipePool { @Override public void loadRecipes() { final IRecipeMap coke = GTCMRecipe.CokingFactoryRecipes; // Raw Radox GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(24), GT_ModHandler.getModItem("GalaxySpace", "barnardaClog", 64)) .fluidInputs(GT_CoreModSupport.Xenoxene.getFluid(1000)) .fluidOutputs(GT_CoreModSupport.RawRadox.getFluid(1000 * 2))
.eut(RECIPE_UV)
2
2023-10-16 09:57:15+00:00
8k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/core/Warehouse.java
[ { "identifier": "IApplicationModule", "path": "GoRouter-Api/src/main/java/com/wyjson/router/interfaces/IApplicationModule.java", "snippet": "public interface IApplicationModule {\n\n int PRIORITY_MAX = 100;\n int PRIORITY_NORM = 50;\n int PRIORITY_MIN = 1;\n\n /**\n * The priority of the module application,\n * which will be executed in order from largest to smallest.\n */\n default int setPriority() {\n return PRIORITY_NORM;\n }\n\n void onCreate(Application app);\n\n /**\n * 优化启动速度,一些不着急的初始化可以放在这里做,子线程\n *\n * @param app\n */\n void onLoadAsync(Application app);\n\n default void onTerminate() {\n\n }\n\n default void onConfigurationChanged(@NonNull Configuration newConfig) {\n\n }\n\n default void onLowMemory() {\n\n }\n\n default void onTrimMemory(int level) {\n\n }\n\n}" }, { "identifier": "IInterceptor", "path": "GoRouter-Api/src/main/java/com/wyjson/router/interfaces/IInterceptor.java", "snippet": "public interface IInterceptor {\n\n void init();\n\n /**\n * {@link InterceptorCallback#onContinue(Card)} 继续执行,\n * {@link InterceptorCallback#onInterrupt(Card, Throwable)}} 拦截\n *\n * @param card\n * @param callback\n */\n void process(Card card, InterceptorCallback callback);\n}" }, { "identifier": "CardMeta", "path": "GoRouter-Api/src/main/java/com/wyjson/router/model/CardMeta.java", "snippet": "public class CardMeta {\n private String path;\n private String group;\n private RouteType type;\n private Class<?> pathClass;\n private int tag;// 额外的标记\n private boolean deprecated;\n private Map<String, ParamMeta> paramsType;// <字段名, 参数元数据对象>\n\n protected CardMeta() {\n }\n\n public CardMeta(String path, RouteType type, Class<?> pathClass, int tag, boolean deprecated, Map<String, ParamMeta> paramsType) {\n setPath(path);\n this.type = type;\n this.pathClass = pathClass;\n this.tag = tag;\n this.deprecated = deprecated;\n this.paramsType = paramsType;\n }\n\n @Nullable\n public String getPath() {\n return path;\n }\n\n public void setPath(@NonNull String path) {\n if (TextUtils.isEmpty(path)) {\n throw new RouterException(\"path Parameter is invalid!\");\n }\n this.path = path;\n this.group = extractGroup(path);\n }\n\n public String getGroup() {\n return group;\n }\n\n private String extractGroup(String path) {\n if (TextUtils.isEmpty(path) || !path.startsWith(\"/\")) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed, the path must be start with '/' and contain more than 2 '/'!\");\n }\n\n try {\n String group = path.substring(1, path.indexOf(\"/\", 1));\n if (TextUtils.isEmpty(group)) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed! There's nothing between 2 '/'!\");\n } else {\n return group;\n }\n } catch (Exception e) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed, the path must be start with '/' and contain more than 2 '/'! \" + e.getMessage());\n }\n }\n\n\n public RouteType getType() {\n return type;\n }\n\n void setType(RouteType type) {\n this.type = type;\n }\n\n public Class<?> getPathClass() {\n return pathClass;\n }\n\n void setPathClass(Class<?> pathClass) {\n this.pathClass = pathClass;\n }\n\n public int getTag() {\n return tag;\n }\n\n void setTag(int tag) {\n this.tag = tag;\n }\n\n public boolean isDeprecated() {\n return deprecated;\n }\n\n void setDeprecated(boolean deprecated) {\n this.deprecated = deprecated;\n }\n\n public Map<String, ParamMeta> getParamsType() {\n if (paramsType == null) {\n paramsType = new HashMap<>();\n }\n return paramsType;\n }\n\n public void commitActivity(@NonNull Class<?> cls) {\n commit(cls, RouteType.ACTIVITY);\n }\n\n public void commitFragment(@NonNull Class<?> cls) {\n commit(cls, RouteType.FRAGMENT);\n }\n\n private void commit(Class<?> cls, RouteType type) {\n if (cls == null) {\n throw new RouterException(\"Cannot commit empty!\");\n }\n RouteCenter.addCardMeta(new CardMeta(this.path, type, cls, this.tag, this.deprecated, this.paramsType));\n }\n\n public CardMeta putTag(int tag) {\n this.tag = tag;\n return this;\n }\n\n /**\n * @param deprecated 如果标记为true,框架在openDebug()的情况下,跳转到该页将提示其他开发人员和测试人员\n * @return\n */\n public CardMeta putDeprecated(boolean deprecated) {\n this.deprecated = deprecated;\n return this;\n }\n\n public CardMeta putObject(String key) {\n return put(key, null, ParamType.Object, false);\n }\n\n public CardMeta putObject(String key, String name, boolean required) {\n return put(key, name, ParamType.Object, required);\n }\n\n public CardMeta putString(String key) {\n return put(key, null, ParamType.String, false);\n }\n\n public CardMeta putString(String key, String name, boolean required) {\n return put(key, name, ParamType.String, required);\n }\n\n public CardMeta putBoolean(String key) {\n return put(key, null, ParamType.Boolean, false);\n }\n\n public CardMeta putBoolean(String key, String name, boolean required) {\n return put(key, name, ParamType.Boolean, required);\n }\n\n public CardMeta putShort(String key) {\n return put(key, null, ParamType.Short, false);\n }\n\n public CardMeta putShort(String key, String name, boolean required) {\n return put(key, name, ParamType.Short, required);\n }\n\n public CardMeta putInt(String key) {\n return put(key, null, ParamType.Int, false);\n }\n\n public CardMeta putInt(String key, String name, boolean required) {\n return put(key, name, ParamType.Int, required);\n }\n\n public CardMeta putLong(String key) {\n return put(key, null, ParamType.Long, false);\n }\n\n public CardMeta putLong(String key, String name, boolean required) {\n return put(key, name, ParamType.Long, required);\n }\n\n public CardMeta putDouble(String key) {\n return put(key, null, ParamType.Double, false);\n }\n\n public CardMeta putDouble(String key, String name, boolean required) {\n return put(key, name, ParamType.Double, required);\n }\n\n public CardMeta putByte(String key) {\n return put(key, null, ParamType.Byte, false);\n }\n\n public CardMeta putByte(String key, String name, boolean required) {\n return put(key, name, ParamType.Byte, required);\n }\n\n public CardMeta putChar(String key) {\n return put(key, null, ParamType.Char, false);\n }\n\n public CardMeta putChar(String key, String name, boolean required) {\n return put(key, name, ParamType.Char, required);\n }\n\n public CardMeta putFloat(String key) {\n return put(key, null, ParamType.Float, false);\n }\n\n public CardMeta putFloat(String key, String name, boolean required) {\n return put(key, name, ParamType.Float, required);\n }\n\n public CardMeta putSerializable(String key) {\n return put(key, null, ParamType.Serializable, false);\n }\n\n public CardMeta putSerializable(String key, String name, boolean required) {\n return put(key, name, ParamType.Serializable, required);\n }\n\n public CardMeta putParcelable(String key) {\n return put(key, null, ParamType.Parcelable, false);\n }\n\n public CardMeta putParcelable(String key, String name, boolean required) {\n return put(key, name, ParamType.Parcelable, required);\n }\n\n private CardMeta put(String key, String name, ParamType type, boolean required) {\n getParamsType().put(key, new ParamMeta(TextUtils.isEmpty(name) ? key : name, type, required));\n return this;\n }\n\n public boolean isTagExist(int item) {\n return RouteTagUtils.isExist(tag, item);\n }\n\n public int getTagExistCount() {\n return RouteTagUtils.getExistCount(tag);\n }\n\n public int addTag(int item) {\n return tag = RouteTagUtils.addItem(tag, item);\n }\n\n public int deleteTag(int item) {\n return tag = RouteTagUtils.deleteItem(tag, item);\n }\n\n public int getTagNegation() {\n return RouteTagUtils.getNegation(tag);\n }\n\n public ArrayList<Integer> getTagExistList(int... itemList) {\n return RouteTagUtils.getExistList(tag, itemList);\n }\n\n @NonNull\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n return \"CardMeta{\" +\n \"path='\" + path + '\\'' +\n \", type=\" + type +\n \", pathClass=\" + pathClass +\n \", tag=\" + tag +\n \", paramsType=\" + paramsType +\n '}';\n }\n}" }, { "identifier": "ServiceMeta", "path": "GoRouter-Api/src/main/java/com/wyjson/router/model/ServiceMeta.java", "snippet": "public class ServiceMeta {\n private final Class<? extends IService> serviceClass;\n private IService service;\n\n public ServiceMeta(Class<? extends IService> serviceClass) {\n this.serviceClass = serviceClass;\n }\n\n public Class<? extends IService> getServiceClass() {\n return serviceClass;\n }\n\n public IService getService() {\n return service;\n }\n\n public void setService(IService service) {\n this.service = service;\n }\n}" }, { "identifier": "IRouteModuleGroup", "path": "GoRouter-Api/src/main/java/com/wyjson/router/module/interfaces/IRouteModuleGroup.java", "snippet": "public interface IRouteModuleGroup {\n void load();\n}" }, { "identifier": "InterceptorTreeMap", "path": "GoRouter-Api/src/main/java/com/wyjson/router/utils/InterceptorTreeMap.java", "snippet": "public class InterceptorTreeMap<K, V> extends TreeMap<K, V> {\n private final String tipText;\n\n public InterceptorTreeMap(String exceptionText) {\n super();\n tipText = exceptionText;\n }\n\n @Override\n public V put(K key, V value) {\n if (containsKey(key)) {\n throw new RouterException(String.format(tipText, key));\n } else {\n return super.put(key, value);\n }\n }\n\n @NonNull\n @Override\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n Iterator<Entry<K, V>> i = entrySet().iterator();\n if (!i.hasNext())\n return \"{}\";\n\n StringBuilder sb = new StringBuilder();\n sb.append('{');\n for (; ; ) {\n Entry<K, V> e = i.next();\n K key = e.getKey();\n V value = e.getValue();\n sb.append(key);\n sb.append(\"->\");\n sb.append(value.getClass().getSimpleName());\n if (!i.hasNext())\n return sb.append('}').toString();\n sb.append(',').append(' ');\n }\n }\n}" }, { "identifier": "RouteGroupHashMap", "path": "GoRouter-Api/src/main/java/com/wyjson/router/utils/RouteGroupHashMap.java", "snippet": "public class RouteGroupHashMap extends HashMap<String, IRouteModuleGroup> {\n\n @Nullable\n @Override\n public IRouteModuleGroup put(String key, IRouteModuleGroup value) {\n // 发现已经存在的分组,直接执行分组里的加载方法,再添加新的路由数据进来\n if (containsKey(key)) {\n try {\n GoRouter.logger.warning(null, \"Discover an existing group[\" + key + \"], execute the loading method in the group, and add new route data.\");\n get(key).load();\n } catch (Exception e) {\n throw new RouterException(\"A fatal exception occurred while loading the route group[\" + key + \"]. [\" + e.getMessage() + \"]\");\n }\n }\n return super.put(key, value);\n }\n\n}" }, { "identifier": "RouteHashMap", "path": "GoRouter-Api/src/main/java/com/wyjson/router/utils/RouteHashMap.java", "snippet": "public class RouteHashMap extends HashMap<String, CardMeta> {\n\n @Nullable\n @Override\n public CardMeta put(String key, CardMeta value) {\n // 检查路由是否有重复提交的情况(仅对使用java注册方式有效)\n if (GoRouter.isDebug()) {\n if (containsKey(key)) {\n GoRouter.logger.error(null, \"route path[\" + key + \"] duplicate commit!!!\");\n } else if (containsValue(value)) {\n GoRouter.logger.error(null, \"route pathClass[\" + value.getPathClass() + \"] duplicate commit!!!\");\n }\n }\n return super.put(key, value);\n }\n\n public boolean containsValue(CardMeta value) {\n if (size() == 0)\n return false;\n for (Map.Entry<String, CardMeta> entry : entrySet()) {\n if (entry.getValue().getPathClass() == value.getPathClass()) {\n return true;\n }\n }\n return false;\n }\n}" }, { "identifier": "ServiceHashMap", "path": "GoRouter-Api/src/main/java/com/wyjson/router/utils/ServiceHashMap.java", "snippet": "public class ServiceHashMap extends HashMap<String, ServiceMeta> {\n\n @Nullable\n @Override\n public ServiceMeta put(String key, ServiceMeta value) {\n // [xx]服务已经在[xxx]实现中注册,并将被覆盖(更新)。\n if (containsKey(key)) {\n GoRouter.logger.warning(null, \"The [\" + key + \"] service has been registered in the [\" + value.getServiceClass().getSimpleName() + \"] implementation and will be overridden (updated).\");\n }\n return super.put(key, value);\n }\n\n}" } ]
import androidx.lifecycle.MutableLiveData; import com.wyjson.router.interfaces.IApplicationModule; import com.wyjson.router.interfaces.IInterceptor; import com.wyjson.router.model.CardMeta; import com.wyjson.router.model.ServiceMeta; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.utils.InterceptorTreeMap; import com.wyjson.router.utils.RouteGroupHashMap; import com.wyjson.router.utils.RouteHashMap; import com.wyjson.router.utils.ServiceHashMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
3,704
package com.wyjson.router.core; class Warehouse { static final List<IApplicationModule> applicationModules = new ArrayList<>(); static final Map<String, IRouteModuleGroup> routeGroups = new RouteGroupHashMap();
package com.wyjson.router.core; class Warehouse { static final List<IApplicationModule> applicationModules = new ArrayList<>(); static final Map<String, IRouteModuleGroup> routeGroups = new RouteGroupHashMap();
static final Map<String, CardMeta> routes = new RouteHashMap();
7
2023-10-18 13:52:07+00:00
8k
trpc-group/trpc-java
trpc-core/src/test/java/com/tencent/trpc/core/rpc/AbstractRpcServerTest.java
[ { "identifier": "ProtocolConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/ProtocolConfig.java", "snippet": "public class ProtocolConfig extends BaseProtocolConfig implements Cloneable {\n\n protected String name;\n protected String ip;\n protected int port;\n protected String nic;\n protected InetSocketAddress address;\n /**\n * Protocol type [stream, standard].\n */\n protected String protocolType;\n protected volatile boolean setDefault = false;\n protected volatile boolean inited = false;\n\n public static ProtocolConfig newInstance() {\n return new ProtocolConfig();\n }\n\n public static String toUniqId(String host, int port, String networkType) {\n return host + Constants.COLON + port + Constants.COLON + networkType;\n }\n\n public String toUniqId() {\n return toUniqId(ip, port, network);\n }\n\n /**\n * Set default values.\n */\n public synchronized void setDefault() {\n if (!setDefault) {\n setFieldDefault();\n setDefault = true;\n }\n }\n\n /**\n * Initialize client service\n */\n public synchronized void init() {\n if (!inited) {\n setDefault();\n inited = true;\n }\n }\n\n /**\n * Set protocol default values.\n */\n protected void setFieldDefault() {\n BinderUtils.bind(this);\n BinderUtils.lazyBind(this, ConfigConstants.IP, nic, obj -> NetUtils.resolveMultiNicAddr((String) obj));\n BinderUtils.bind(this, ConfigConstants.IO_THREADS, Constants.DEFAULT_IO_THREADS);\n PreconditionUtils.checkArgument(StringUtils.isNotBlank(ip), \"Protocol(%s), ip is null\", toSimpleString());\n BinderUtils.bind(this, \"address\", new InetSocketAddress(this.getIp(), this.getPort()));\n }\n\n public RpcClient createClient() {\n setDefault();\n RpcClientFactory extension = ExtensionLoader.getExtensionLoader(RpcClientFactory.class)\n .getExtension(getProtocol());\n PreconditionUtils.checkArgument(extension != null, \"rpc client extension %s not exist\",\n getProtocol());\n return extension.createRpcClient(this);\n }\n\n public RpcServer createServer() {\n setDefault();\n return RpcServerManager.getOrCreateRpcServer(this);\n }\n\n @Override\n public String toString() {\n return \"ProtocolConfig [name=\" + name + \", ip=\" + ip + \", port=\" + port + \", nic=\" + nic\n + \", address=\" + address + \", protocol=\" + protocol + \", serializationType=\"\n + serialization\n + \", compressorType=\" + compressor + \", keepAlive=\" + keepAlive + \", charset=\"\n + charset\n + \", transporter=\" + transporter + \", maxConns=\" + maxConns + \", backlog=\" + backlog\n + \", network=\" + network + \", receiveBuffer=\" + receiveBuffer + \", sendBuffer=\"\n + sendBuffer\n + \", payload=\" + payload + \", idleTimeout=\" + idleTimeout + \", lazyinit=\" + lazyinit\n + \", connsPerAddr=\" + connsPerAddr + \", connTimeout=\" + connTimeout + \", ioMode=\"\n + ioMode\n + \", ioThreadGroupShare=\" + ioThreadGroupShare + \", ioThreads=\" + ioThreads\n + \", extMap=\"\n + extMap + \", setDefault=\" + setDefault + \"]\";\n }\n\n public ProtocolConfig clone() {\n ProtocolConfig newConfig = null;\n try {\n newConfig = (ProtocolConfig) super.clone();\n } catch (CloneNotSupportedException ex) {\n throw new RuntimeException(\"\", ex);\n }\n newConfig.inited = false;\n newConfig.setDefault = false;\n newConfig.setExtMap(new HashMap<>(this.getExtMap()));\n return newConfig;\n }\n\n /**\n * Convert to InetSocketAddress.\n *\n * @return InetSocketAddress\n */\n public InetSocketAddress toInetSocketAddress() {\n if (address == null) {\n if (StringUtils.isNotBlank(ip)) {\n return new InetSocketAddress(ip, port);\n }\n }\n return address;\n }\n\n /**\n * Registration information: Polaris name + protocol + ip + port + network.\n *\n * @return Polaris name + protocol + ip + port + network\n */\n public String toSimpleString() {\n return (name == null ? \"<null>\" : name) + \":\" + protocol + \":\" + ip + \":\" + port + \":\" + network;\n }\n\n public boolean useEpoll() {\n return StringUtils.equalsIgnoreCase(ioMode, Constants.IO_MODE_EPOLL);\n }\n\n @Override\n protected void checkFiledModifyPrivilege() {\n super.checkFiledModifyPrivilege();\n Preconditions.checkArgument(!isInited(), \"Not allow to modify field,state is(init)\");\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n checkFiledModifyPrivilege();\n this.name = name;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(String ip) {\n checkFiledModifyPrivilege();\n this.ip = ip;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n checkFiledModifyPrivilege();\n this.port = port;\n }\n\n public Boolean isKeepAlive() {\n return keepAlive;\n }\n\n public Boolean isLazyinit() {\n return lazyinit;\n }\n\n public Boolean isIoThreadGroupShare() {\n return ioThreadGroupShare;\n }\n\n @Override\n public void setBossThreads(int bossThreads) {\n checkFiledModifyPrivilege();\n Preconditions.checkArgument(bossThreads < Runtime.getRuntime().availableProcessors() * 4,\n \"boss threads Cannot be greater than CPU * 4:\" + Runtime.getRuntime().availableProcessors() * 4);\n Preconditions.checkArgument(bossThreads < ioThreads,\n \"boss threads Cannot be greater than io Threads:\" + this.ioThreads);\n this.bossThreads = bossThreads;\n }\n\n public String getNic() {\n return nic;\n }\n\n public void setNic(String nic) {\n checkFiledModifyPrivilege();\n this.nic = nic;\n }\n\n public String getProtocolType() {\n return protocolType;\n }\n\n public void setProtocolType(String protocolType) {\n checkFiledModifyPrivilege();\n this.protocolType = protocolType;\n }\n\n public boolean isSetDefault() {\n return setDefault;\n }\n\n public boolean isInited() {\n return inited;\n }\n\n}" }, { "identifier": "ProviderConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/ProviderConfig.java", "snippet": "public class ProviderConfig<T> implements Cloneable {\n\n protected static final Logger logger = LoggerFactory.getLogger(ProviderConfig.class);\n /**\n * Business service related configuration.\n */\n protected Class<T> serviceInterface;\n /**\n * Fully qualified class name of the provider implementation.\n */\n @ConfigProperty(name = \"impl\")\n protected String refClazz;\n protected T ref;\n /**\n * Service related configuration.\n */\n protected ServiceConfig serviceConfig;\n /**\n * Request timeout duration.\n */\n @ConfigProperty(value = Constants.DEFAULT_SERVER_TIMEOUT_MS, type = Integer.class, override = true)\n protected int requestTimeout;\n /**\n * Thread pool configuration.\n */\n @ConfigProperty(value = WorkerPoolManager.DEF_PROVIDER_WORKER_POOL_NAME, override = true)\n protected String workerPool;\n /**\n * Whether to disable default filters:\n * <p>{@link com.tencent.trpc.core.filter.ProviderInvokerHeadFilter}</p>\n * <p>{@link com.tencent.trpc.core.filter.ProviderInvokerTailFilter}</p>\n */\n @ConfigProperty(value = \"false\", type = Boolean.class)\n protected Boolean disableDefaultFilter;\n /**\n * Filter configuration.\n */\n @ConfigProperty\n protected List<String> filters;\n /**\n * Whether to enable full link timeout.\n */\n @ConfigProperty(value = \"false\", type = Boolean.class, override = true)\n protected Boolean enableLinkTimeout;\n /**\n * Worker pool.\n */\n protected WorkerPool workerPoolObj;\n protected volatile boolean setDefault = false;\n protected volatile boolean inited = false;\n\n public static <T> ProviderConfig<T> newInstance() {\n return new ProviderConfig<T>();\n }\n\n public synchronized void init() {\n if (!inited) {\n setDefault();\n initServiceInterfaceConfig();\n validateFilterConfig();\n initWorkerPool();\n inited = true;\n logger.info(\"Init ProviderConfig, inited info: \" + toString());\n }\n }\n\n /**\n * Set default values.\n */\n public synchronized void setDefault() {\n if (!setDefault) {\n setFieldDefault();\n setDefault = true;\n }\n }\n\n /**\n * Service configuration prioritizes server:service node configurations. When there is no configuration and the\n * value is allowed to be overridden, we use the global configuration for overriding.\n * Finally, set the default value {@link ServiceConfig#setFiledDefault()}.\n *\n * @param serviceConfig service config\n */\n public void overrideConfigDefault(ServiceConfig serviceConfig) {\n Objects.requireNonNull(serviceConfig, \"serviceConfig\");\n BinderUtils.bind(this, serviceConfig, Boolean.TRUE);\n BinderUtils.bind(this, ConfigConstants.DISABLE_DEFAULT_FILTER, serviceConfig.getDisableDefaultFilter());\n BinderUtils.bind(this, ConfigConstants.FILTERS, CollectionUtils.isNotEmpty(serviceConfig.getFilters())\n ? serviceConfig.getFilters() : Lists.newArrayList());\n }\n\n /**\n * Set default values.\n */\n protected void setFieldDefault() {\n BinderUtils.bind(this);\n }\n\n /**\n * Validate filter.\n */\n protected void validateFilterConfig() {\n Optional.ofNullable(getFilters()).ifPresent(fs -> fs.forEach(FilterManager::validate));\n }\n\n /**\n * Initialize the thread pool.\n */\n protected void initWorkerPool() {\n String workerPool = getWorkerPool();\n Objects.requireNonNull(workerPool, \"workerPoolName\");\n WorkerPoolManager.validate(workerPool);\n workerPoolObj = WorkerPoolManager.get(workerPool);\n Objects.requireNonNull(workerPoolObj, \"Not found worker pool with name <\" + workerPool + \">\");\n }\n\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public ProviderConfig<T> clone() {\n try {\n ProviderConfig<T> config = (ProviderConfig<T>) super.clone();\n config.resetFlag();\n return config;\n } catch (CloneNotSupportedException e) {\n throw new RuntimeException(\"\", e);\n }\n }\n\n protected void resetFlag() {\n this.setDefault = false;\n this.inited = false;\n }\n\n /**\n * Ensure ref, serviceInterface, and refClazz are all assigned.\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n protected void initServiceInterfaceConfig() {\n // 1) Ensure ref\n if (ref == null) {\n if (StringUtils.isNotBlank(refClazz)) {\n try {\n this.ref = (T) ClassLoaderUtils.getClassLoader(this.getClass()).loadClass(this.refClazz)\n .newInstance();\n } catch (Exception e) {\n throw new RuntimeException(\"refClazz(\" + refClazz + \") new instance exception\", e);\n }\n }\n }\n Preconditions.checkArgument(getRef() != null, \"ServiceImpl is null\");\n // 2) Ensure serviceInterface\n if (serviceInterface == null) {\n // First find the one with RpcService annotation, if empty, use the first one by default\n Class[] interfaces = ref.getClass().getInterfaces();\n PreconditionUtils.checkArgument(interfaces.length >= 1, \"serviceImpl(%s) no interface\",\n ref.getClass());\n for (Class each : interfaces) {\n if (each.getAnnotation(TRpcService.class) != null) {\n serviceInterface = each;\n }\n }\n if (serviceInterface != null) {\n serviceInterface = interfaces[0];\n }\n }\n Preconditions.checkArgument(getServiceInterface() != null, \"ServiceInterface is null\");\n // 3) For Spring rewriting, the clazz type will not be the real type. So only assign here if it's null\n if (this.refClazz == null) {\n this.refClazz = ref.getClass().getName();\n }\n if (!getServiceInterface().isAssignableFrom(ref.getClass())) {\n throw new IllegalArgumentException(\"ServiceImpl must be sub class of class:\"\n + getServiceInterface() + \", serviceImpl: \" + getRefClassName());\n }\n }\n\n public String getRefClassName() {\n return ref == null ? \"<NULL>\" : ref.getClass().getName();\n }\n\n public WorkerPool getWorkerPoolObj() {\n return workerPoolObj;\n\n }\n\n @Override\n public String toString() {\n return \"ProviderConfig {serviceInterface=\" + serviceInterface + \", serviceImplClazz=\"\n + getRefClassName() + \", ref=\" + ref + \", inited=\" + inited + \"}\";\n }\n\n protected void checkFiledModifyPrivilege() {\n Preconditions.checkArgument(!isInited(), \"Not allow to modify field,state is(init)\");\n }\n\n public Class<T> getServiceInterface() {\n return serviceInterface;\n }\n\n public void setServiceInterface(Class<T> serviceInterface) {\n checkFiledModifyPrivilege();\n this.serviceInterface = serviceInterface;\n }\n\n public String getRefClazz() {\n return refClazz;\n }\n\n public void setRefClazz(String refClazz) {\n checkFiledModifyPrivilege();\n this.refClazz = refClazz;\n }\n\n public T getRef() {\n return ref;\n }\n\n public void setRef(T ref) {\n checkFiledModifyPrivilege();\n Objects.requireNonNull(ref, \"ref\");\n this.ref = ref;\n }\n\n public ServiceConfig getServiceConfig() {\n return serviceConfig;\n }\n\n public void setServiceConfig(ServiceConfig serviceConfig) {\n checkFiledModifyPrivilege();\n this.serviceConfig = serviceConfig;\n }\n\n public boolean isInited() {\n return inited;\n }\n\n public boolean isSetDefault() {\n return setDefault;\n }\n\n public int getRequestTimeout() {\n if (requestTimeout > 0) {\n return requestTimeout;\n }\n // 兼容通过配置类的方式\n return serviceConfig.getRequestTimeout();\n }\n\n public void setRequestTimeout(int requestTimeout) {\n checkFiledModifyPrivilege();\n this.requestTimeout = requestTimeout;\n }\n\n public String getWorkerPool() {\n if (null != workerPool) {\n return workerPool;\n }\n // compatible with configuration class method\n return serviceConfig.getWorkerPool();\n }\n\n public void setWorkerPool(String workerPool) {\n checkFiledModifyPrivilege();\n this.workerPool = workerPool;\n }\n\n public Boolean getDisableDefaultFilter() {\n return disableDefaultFilter;\n }\n\n public void setDisableDefaultFilter(Boolean disableDefaultFilter) {\n checkFiledModifyPrivilege();\n this.disableDefaultFilter = disableDefaultFilter;\n }\n\n public List<String> getFilters() {\n if (CollectionUtils.isNotEmpty(filters)) {\n return filters;\n }\n // compatible with configuration class method\n return serviceConfig.getFilters();\n }\n\n public void setFilters(List<String> filters) {\n checkFiledModifyPrivilege();\n this.filters = filters;\n }\n\n public Boolean getEnableLinkTimeout() {\n if (null != enableLinkTimeout) {\n return enableLinkTimeout;\n }\n // compatible with configuration class method\n return serviceConfig.getEnableLinkTimeout();\n }\n\n public void setEnableLinkTimeout(Boolean enableLinkTimeout) {\n checkFiledModifyPrivilege();\n this.enableLinkTimeout = enableLinkTimeout;\n }\n\n}" }, { "identifier": "DefProviderInvoker", "path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/def/DefProviderInvoker.java", "snippet": "public class DefProviderInvoker<T> implements ProviderInvoker<T> {\n\n private static final Logger LOG = LoggerFactory.getLogger(DefProviderInvoker.class);\n private ProtocolConfig config;\n private ProviderConfig<T> providerConfig;\n private Map<String, Method> rpcMethodMap = Maps.newHashMap();\n\n /**\n * Provider constructor.\n *\n * @param config protocol-related configuration\n * @param pConfig configuration related to the service interface list\n */\n public DefProviderInvoker(ProtocolConfig config, ProviderConfig<T> pConfig) {\n this.config = config;\n this.providerConfig = pConfig;\n Class<T> serviceType = pConfig.getServiceInterface();\n Arrays.stream(serviceType.getDeclaredMethods()).forEach(method -> {\n String rpcMethodName = RpcUtils.parseRpcMethodName(method, null);\n if (rpcMethodName == null) {\n LOG.warn(\"Gen providerInvoker error, parse interface={}, which has no rpc method name\",\n serviceType.getName());\n return;\n }\n PreconditionUtils.checkArgument(!rpcMethodMap.containsKey(rpcMethodName),\n \"interface=[%s], rpcMethod[%s], duplicate\", serviceType.getName(),\n rpcMethodName);\n rpcMethodMap.put(rpcMethodName, method);\n });\n PreconditionUtils.checkArgument(pConfig.getRef() != null, \"providerConfig ref is null\");\n }\n\n /**\n * Get the timeout for the current request.\n *\n * @param request request object\n * @param costTime elapsed time in ms\n * @return timeout in ms\n */\n private LeftTimeout parseTimeout(final Request request, final long costTime) {\n // The timeout set by the caller, minus the network time, queue waiting time, etc. to get the remaining time\n int reqLeftTimeout = request.getMeta().getTimeout() - (int) costTime;\n // The timeout set by the callee\n long methodTimeout = getConfig().getRequestTimeout();\n if (request.getMeta().getTimeout() > 0 && methodTimeout > 0) {\n return new LeftTimeout(\n Math.min(request.getMeta().getTimeout(), (int) methodTimeout),\n Math.min(reqLeftTimeout, (int) methodTimeout));\n } else if (request.getMeta().getTimeout() > 0) {\n return new LeftTimeout(request.getMeta().getTimeout(), reqLeftTimeout);\n } else if (methodTimeout > 0) {\n return new LeftTimeout((int) methodTimeout, (int) methodTimeout);\n } else {\n return new LeftTimeout(Constants.DEFAULT_TIMEOUT, Constants.DEFAULT_TIMEOUT);\n }\n }\n\n @Override\n public CompletionStage<Response> invoke(Request request) {\n RpcContext context = request.getContext();\n RpcInvocation invocation = request.getInvocation();\n Object[] params = ArrayUtils.addAll(new Object[]{context}, invocation.getArguments());\n CompletableFuture<Response> responseFuture = new CompletableFuture<>();\n try {\n Method method = rpcMethodMap.get(invocation.getRpcMethodName());\n // unexpected cases theoretically do not exist\n if (method == null) {\n responseFuture.complete(RpcUtils.newResponse(request, null,\n TRpcException.newFrameException(ErrorCode.TRPC_INVOKE_UNKNOWN_ERR,\n \"Unknown rpcMethod[\" + invocation.getRpcMethodName()\n + \"]\")));\n return responseFuture;\n }\n long costTime = System.currentTimeMillis() - request.getMeta().getCreateTime();\n LeftTimeout leftTimeout = parseTimeout(request, costTime);\n long leftTime = leftTimeout.getLeftTimeout();\n long originTimeout = leftTimeout.getOriginTimeout();\n if (leftTime <= 0) {\n throw TRpcException.newFrameException(ErrorCode.TRPC_SERVER_TIMEOUT_ERR,\n \"cost time = \" + costTime + \"ms and timeout=\" + originTimeout + \" ms\");\n }\n // put the full link timeout information into the Context\n RpcContextUtils.putValueMapValue(context, RpcContextValueKeys.CTX_LINK_INVOKE_TIMEOUT,\n LinkInvokeTimeout.builder()\n .startTime(System.currentTimeMillis())\n .timeout(originTimeout)\n .leftTimeout(leftTime)\n .serviceEnableLinkTimeout(getConfig().getEnableLinkTimeout())\n .build());\n\n T serviceImpl = providerConfig.getRef();\n Object result = method.invoke(serviceImpl, params);\n if (InvokeMode.isAsync(invocation.getInvokeMode())) {\n PreconditionUtils.checkArgument(result != null,\n \"Found invoker(rpcServiceName=%s, rpcMethodName=%s) return value is null\",\n invocation.getRpcServiceName(), invocation.getRpcMethodName());\n // 1) asynchronous call on the server side\n return ((CompletionStage<?>) result)\n .thenApply((obj) -> RpcUtils.newResponse(request, obj, null));\n }\n // 2) support synchronous call on the server side\n responseFuture.complete(RpcUtils.newResponse(request, result, null));\n } catch (Throwable ex) {\n if (ex instanceof InvocationTargetException) {\n providerConfig.getWorkerPoolObj().getUncaughtExceptionHandler()\n .uncaughtException(Thread.currentThread(), ex.getCause());\n responseFuture.complete(RpcUtils.newResponse(request, null, ex.getCause()));\n } else {\n providerConfig.getWorkerPoolObj().getUncaughtExceptionHandler()\n .uncaughtException(Thread.currentThread(), ex);\n responseFuture.complete(RpcUtils.newResponse(request, null, ex));\n }\n }\n return responseFuture;\n }\n\n @Override\n public Class<T> getInterface() {\n return providerConfig.getServiceInterface();\n }\n\n @Override\n public ProtocolConfig getProtocolConfig() {\n return config;\n }\n\n @Override\n public T getImpl() {\n return providerConfig.getRef();\n }\n\n @Override\n public ProviderConfig<T> getConfig() {\n return providerConfig;\n }\n\n}" } ]
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.common.config.ProviderConfig; import com.tencent.trpc.core.rpc.def.DefProviderInvoker; import java.util.concurrent.CompletionStage; import org.junit.Before; import org.junit.Test;
5,702
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc; public class AbstractRpcServerTest { private AbstractRpcServer abstractRpcServer; private ProtocolConfig protocolConfig; @Before public void setUp() { abstractRpcServer = new AbstractRpcServer() { @Override protected <T> void doExport(ProviderInvoker<T> invoker) { } @Override protected <T> void doUnExport(ProviderConfig<T> config) { } @Override protected void doOpen() throws Exception { } @Override protected void doClose() { } }; protocolConfig = new ProtocolConfig(); protocolConfig.setIp("127.0.0.1"); protocolConfig.setPort(12345); abstractRpcServer.setConfig(protocolConfig); } @Test public void testExport() { ProviderConfig<GenericClient> objectProviderConfig = new ProviderConfig<>(); objectProviderConfig.setServiceInterface(GenericClient.class); objectProviderConfig.setRef(new GenericClient() { @Override public CompletionStage<byte[]> asyncInvoke(RpcClientContext context, byte[] body) { return null; } @Override public byte[] invoke(RpcClientContext context, byte[] body) { return new byte[0]; } });
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc; public class AbstractRpcServerTest { private AbstractRpcServer abstractRpcServer; private ProtocolConfig protocolConfig; @Before public void setUp() { abstractRpcServer = new AbstractRpcServer() { @Override protected <T> void doExport(ProviderInvoker<T> invoker) { } @Override protected <T> void doUnExport(ProviderConfig<T> config) { } @Override protected void doOpen() throws Exception { } @Override protected void doClose() { } }; protocolConfig = new ProtocolConfig(); protocolConfig.setIp("127.0.0.1"); protocolConfig.setPort(12345); abstractRpcServer.setConfig(protocolConfig); } @Test public void testExport() { ProviderConfig<GenericClient> objectProviderConfig = new ProviderConfig<>(); objectProviderConfig.setServiceInterface(GenericClient.class); objectProviderConfig.setRef(new GenericClient() { @Override public CompletionStage<byte[]> asyncInvoke(RpcClientContext context, byte[] body) { return null; } @Override public byte[] invoke(RpcClientContext context, byte[] body) { return new byte[0]; } });
abstractRpcServer.export(new DefProviderInvoker<>(protocolConfig, objectProviderConfig));
2
2023-10-19 10:54:11+00:00
8k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/rxObservables/FindCommentObservableOnSubscribe.java
[ { "identifier": "Config", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/Config.java", "snippet": "public class Config {\r\n public static final int SORT_RULER_DATE_DESC = 0;\r\n public static final int SORT_RULER_DATE_ASC = 1;\r\n private final SharedPreferences sp_config;\r\n\r\n\r\n public Config(Context context) {\r\n sp_config = context.getSharedPreferences(\"config\",Context.MODE_PRIVATE);\r\n }\r\n\r\n public void setEnableRecordingHistoricalComments(boolean enable){\r\n sp_config.edit().putBoolean(\"recording_historical_comments\",enable).apply();\r\n }\r\n\r\n public boolean getEnableRecordingHistoricalComments(){\r\n return sp_config.getBoolean(\"recording_historical_comments\",true);\r\n }\r\n\r\n public void setWaitTimeAfterCommentSent(long waitTime){\r\n sp_config.edit().putLong(\"wait_time_after_comment_sent\",waitTime).apply();\r\n }\r\n\r\n public long getWaitTimeAfterCommentSent(){\r\n return sp_config.getLong(\"wait_time_after_comment_sent\", 15000);\r\n }\r\n\r\n public void setIntervalOfSearchAgain(long interval){\r\n sp_config.edit().putLong(\"interval_of_search_again\",interval).apply();\r\n }\r\n\r\n public long getIntervalOfSearchAgain(){\r\n return sp_config.getLong(\"interval_of_search_again\",5000);\r\n }\r\n\r\n public void setMaximumNumberOfSearchAgain(int maximumNumberOfSearchAgain){\r\n sp_config.edit().putInt(\"maximum_number_of_search_again\",maximumNumberOfSearchAgain).apply();\r\n }\r\n\r\n public int getMaximumNumberOfSearchAgain(){\r\n return sp_config.getInt(\"maximum_number_of_search_again\",6);\r\n }\r\n\r\n public void setWaitTimeByBackstage(long time){\r\n sp_config.edit().putLong(\"wait_time_by_backstage\",time).apply();\r\n }\r\n\r\n public long getWaitTimeByBackstage(){\r\n return sp_config.getLong(\"wait_time_by_backstage\", 120);\r\n }\r\n\r\n public void setFilterRulerEnableNormal(boolean enable){\r\n sp_config.edit().putBoolean(\"filter_ruler_enable_normal\",enable).apply();\r\n }\r\n\r\n public boolean getFilterRulerEnableNormal(){\r\n return sp_config.getBoolean(\"filter_ruler_enable_normal\", true);\r\n }\r\n\r\n public void setFilterRulerEnableShadowBan(boolean enable){\r\n sp_config.edit().putBoolean(\"filter_ruler_enable_shadow_ban\",enable).apply();\r\n }\r\n\r\n public boolean getFilterRulerEnableShadowBan(){\r\n return sp_config.getBoolean(\"filter_ruler_enable_shadow_ban\",true);\r\n }\r\n\r\n public void setFilterRulerEnableDeleted(boolean enable){\r\n sp_config.edit().putBoolean(\"filter_ruler_enable_deleted\",enable).apply();\r\n }\r\n\r\n public boolean getFilterRulerEnableDelete(){\r\n return sp_config.getBoolean(\"filter_ruler_enable_deleted\",true);\r\n }\r\n\r\n public void setSortRuler(int sortRuler){\r\n sp_config.edit().putInt(\"sort_ruler\",sortRuler).apply();\r\n }\r\n\r\n public int getSortRuler(){\r\n return sp_config.getInt(\"sort_ruler\", SORT_RULER_DATE_DESC);\r\n }\r\n\r\n\r\n}\r" }, { "identifier": "Comment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/Comment.java", "snippet": "public class Comment {\r\n public String commentText;\r\n public String commentId;\r\n\r\n public Comment() {\r\n }\r\n\r\n\r\n public Comment(String commentText, String commentId) {\r\n this.commentText = commentText;\r\n this.commentId = commentId;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"Comment{\" +\r\n \"commentText='\" + commentText + '\\'' +\r\n \", commentId='\" + commentId + '\\'' +\r\n '}';\r\n }\r\n}\r" }, { "identifier": "HistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/HistoryComment.java", "snippet": "public abstract class HistoryComment extends Comment{\r\n public static final String STATE_NORMAL = \"NORMAL\";\r\n public static final String STATE_SHADOW_BAN = \"SHADOW_BAN\";\r\n public static final String STATE_DELETED = \"DELETED\";\r\n\r\n public String state;\r\n public Date sendDate;\r\n @Nullable\r\n public Comment anchorComment;\r\n @Nullable\r\n public Comment repliedComment;\r\n\r\n public HistoryComment(){}\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment) {\r\n this(commentText,commentId,state,sendDate);\r\n this.anchorComment = anchorComment;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n this.anchorComment = anchorComment;\r\n this.repliedComment = repliedComment;\r\n }\r\n\r\n public abstract String getCommentSectionSourceId();\r\n\r\n public String getFormatDateFor_yMd(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n}\r" }, { "identifier": "ToBeCheckedComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/ToBeCheckedComment.java", "snippet": "public class ToBeCheckedComment extends Comment{\r\n public static final int COMMENT_SECTION_TYPE_VIDEO = 1;\r\n\r\n public String sourceId;\r\n public int commentSectionType;\r\n public String repliedCommentId;\r\n public String repliedCommentText;\r\n public byte[] context1;\r\n public Date sendTime;\r\n\r\n public ToBeCheckedComment(String commentId, String commentText, String sourceId, int commentSectionType, String repliedCommentId, String repliedCommentText, byte[] context1,Date sendTime) {\r\n this.commentId = commentId;\r\n this.commentText = commentText;\r\n this.sourceId = sourceId;\r\n this.commentSectionType = commentSectionType;\r\n this.repliedCommentId = repliedCommentId;\r\n this.repliedCommentText = repliedCommentText;\r\n this.context1 = context1;\r\n this.sendTime = sendTime;\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendTime);\r\n }\r\n\r\n\r\n\r\n}\r" }, { "identifier": "VideoComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoComment.java", "snippet": "public class VideoComment extends Comment{\r\n public String videoId;\r\n\r\n public VideoComment(String commentText, String commentId, String videoId) {\r\n super(commentText, commentId);\r\n this.videoId = videoId;\r\n }\r\n}\r" }, { "identifier": "VideoCommentSection", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoCommentSection.java", "snippet": "public class VideoCommentSection extends CommentSection {\r\n\r\n private final byte[] contextPbData;\r\n private boolean hasAccount;\r\n private final Bundle headersBundle;\r\n\r\n private final String firstContinuationBase64Text;\r\n private String currentContinuationBase64Text;\r\n\r\n public VideoCommentSection(OkHttpClient okHttpClient, byte[] contextPbData, String continuationBase64Text, Bundle headersBundle, boolean hasAccount) {\r\n super(okHttpClient);\r\n this.contextPbData = contextPbData;\r\n this.firstContinuationBase64Text = continuationBase64Text;\r\n this.currentContinuationBase64Text = firstContinuationBase64Text;\r\n this.headersBundle = headersBundle;\r\n this.hasAccount = hasAccount;\r\n }\r\n\r\n @Override\r\n public boolean nextPage() throws IOException, Code401Exception {\r\n if (currentContinuationBase64Text != null) {\r\n currentCommentList = new ArrayList<>();\r\n //VideoCommentRequest.Builder builder = VideoCommentRequest.newBuilder();\r\n //builder.setContext(Context.parseFrom(contextPbData));\r\n //builder.setContinuation(continuationBase64Text);\r\n //VideoCommentRequest videoCommentRequest = builder.build();\r\n VideoCommentRequest videoCommentRequest1 = VideoCommentRequest.newBuilder().setContext(Context.parseFrom(contextPbData)).setContinuation(currentContinuationBase64Text).build();\r\n RequestBody requestBody = RequestBody.create(videoCommentRequest1.toByteArray(), MediaType.parse(\"application/x-protobuf\"));\r\n Request.Builder requestBuilder = new Request.Builder()\r\n .url(\"https://youtubei.googleapis.com/youtubei/v1/next?key=AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w\")\r\n .addHeader(\"X-GOOG-API-FORMAT-VERSION\",headersBundle.getString(\"X-GOOG-API-FORMAT-VERSION\"))\r\n .addHeader(\"X-Goog-Visitor-Id\",headersBundle.getString(\"X-Goog-Visitor-Id\"))\r\n .addHeader(\"User-Agent\",headersBundle.getString(\"User-Agent\"))\r\n .post(requestBody);\r\n if (hasAccount){\r\n requestBuilder.addHeader(\"Authorization\", headersBundle.getString(\"Authorization\"));//跟cookie一样的作用\r\n }\r\n Request request = requestBuilder.build();\r\n Response response = okHttpClient.newCall(request).execute();\r\n if (response.code() == 401){\r\n throw new Code401Exception(\"Received status code 401, the token may have expired\");\r\n }\r\n ResponseBody body = response.body();\r\n OkHttpUtils.checkResponseBodyNotNull(body);\r\n\r\n VideoCommentResponse videoCommentResponse = VideoCommentResponse.parseFrom(body.bytes());\r\n List<ContinuationItem> continuationItemList = videoCommentResponse.getContinuationItemsAction().getContinuationItems().getContinuationItemList();\r\n for (ContinuationItem continuationItem : continuationItemList) {\r\n if (continuationItem.getUnk3().hasComment()) {\r\n icu.freedomintrovert.YTSendCommAntiFraud.grpcApi.Comment comment = continuationItem.getUnk3().getComment();\r\n currentCommentList.add(new Comment(comment.getContent().getMsg().getMessage(),comment.getContent().getCommentId()));\r\n }\r\n }\r\n\r\n NextInfo8 nextInfo8 = videoCommentResponse.getNextInfo8();\r\n if (nextInfo8.hasUnkMsg50195462()) {\r\n for (UnkMsg50195462.UnkMsg2 unkMsg2 : nextInfo8.getUnkMsg50195462().getUnkMsg2List()) {\r\n if (unkMsg2.hasUnkMsg52047593()) {\r\n currentContinuationBase64Text = unkMsg2.getUnkMsg52047593().getContinuation();\r\n return true;\r\n }\r\n }\r\n } else {\r\n for (UnkMsg49399797.UnkMsg49399797_1 unkMsg49399797_1 : nextInfo8.getUnkMsg49399797().getUnkMsg1List()) {\r\n List<UnkMsg50195462.UnkMsg2> unkMsg2List = unkMsg49399797_1.getUnkMsg50195462().getUnkMsg2List();\r\n for (UnkMsg50195462.UnkMsg2 unkMsg2 : unkMsg2List) {\r\n if (unkMsg2.hasUnkMsg52047593()) {\r\n currentContinuationBase64Text = unkMsg2.getUnkMsg52047593().getContinuation();\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n currentContinuationBase64Text = null;\r\n return true;\r\n //stringBuilder.append(\"\\n\" + videoCommentResponse);\r\n }\r\n currentCommentList = null;\r\n return false;\r\n }\r\n\r\n public void reset(boolean hasAccount){\r\n currentContinuationBase64Text = firstContinuationBase64Text;\r\n this.hasAccount = hasAccount;\r\n }\r\n\r\n public String getCurrentContinuationBase64Text(){\r\n return currentContinuationBase64Text;\r\n }\r\n\r\n public byte[] getContextPbData() {\r\n return contextPbData;\r\n }\r\n\r\n public static class Code401Exception extends Exception{\r\n public Code401Exception(String message) {\r\n super(message);\r\n }\r\n }\r\n}\r" }, { "identifier": "VideoHistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoHistoryComment.java", "snippet": "public class VideoHistoryComment extends HistoryComment{\r\n\r\n public String videoId;\r\n\r\n public VideoHistoryComment(String commentId, String commentText, String anchorCommentId, String anchorCommentText, String videoId, String state, long sendDate, String repliedCommentId, String repliedCommentText) {\r\n this.commentId = commentId;\r\n this.commentText = commentText;\r\n if (!TextUtils.isEmpty(anchorCommentId) && anchorCommentText != null) {\r\n this.anchorComment = new Comment(anchorCommentText,anchorCommentId);\r\n }\r\n this.videoId = videoId;\r\n this.state = state;\r\n this.sendDate = new Date(sendDate);\r\n if (!TextUtils.isEmpty(repliedCommentId) && repliedCommentText != null){\r\n this.repliedComment = new Comment(repliedCommentText,repliedCommentId);\r\n }\r\n }\r\n\r\n public VideoHistoryComment(String commentText, String commentId, String state, Date sendDate, String videoId) {\r\n super(commentText, commentId, state, sendDate);\r\n this.videoId = videoId;\r\n }\r\n\r\n public VideoHistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, String videoId) {\r\n super(commentText, commentId, state, sendDate, anchorComment);\r\n this.videoId = videoId;\r\n }\r\n\r\n public VideoHistoryComment(String commentId,String commentText, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment, String videoId) {\r\n super(commentText, commentId, state, sendDate, anchorComment, repliedComment);\r\n this.videoId = videoId;\r\n }\r\n\r\n @Override\r\n public String getCommentSectionSourceId() {\r\n return videoId;\r\n }\r\n\r\n @NonNull\r\n @Override\r\n public String toString() {\r\n return \"VideoHistoryComment{\" +\r\n \"videoId='\" + videoId + '\\'' +\r\n \", state='\" + state + '\\'' +\r\n \", sendDate=\" + sendDate +\r\n \", anchorComment=\" + anchorComment +\r\n \", commentText='\" + commentText + '\\'' +\r\n \", commentId='\" + commentId + '\\'' +\r\n '}';\r\n }\r\n}\r" }, { "identifier": "StatisticsDB", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/db/StatisticsDB.java", "snippet": "public class StatisticsDB extends SQLiteOpenHelper {\r\n public static final String TABLE_NAME_VIDEO_HISTORY_COMMENTS = \"history_comments_from_video\";\r\n private static final String TABLE_NAME_TO_BE_CHECKED_COMMENTS = \"to_be_checked_comments\";\r\n SQLiteDatabase db;\r\n\r\n public static final int DB_VERSION = 1;\r\n\r\n public StatisticsDB(@Nullable Context context) {\r\n super(context, \"statistics\", null, DB_VERSION);\r\n db = getWritableDatabase();\r\n }\r\n\r\n @Override\r\n public void onCreate(SQLiteDatabase db) {\r\n db.execSQL(\"CREATE TABLE history_comments_from_video ( comment_id TEXT PRIMARY KEY UNIQUE NOT NULL, comment_text TEXT NOT NULL,anchor_comment_id TEXT,anchor_comment_text TEXT, video_id TEXT NOT NULL, state TEXT NOT NULL,send_date INTEGER NOT NULL,replied_comment_id TEXT,replied_comment_text TEXT ); \");\r\n db.execSQL(\"CREATE TABLE to_be_checked_comments ( comment_id TEXT PRIMARY KEY NOT NULL UNIQUE, comment_text TEXT NOT NULL, source_id TEXT NOT NULL, comment_section_type INTEGER NOT NULL, replied_comment_id TEXT, replied_comment_text TEXT, context1 BLOB NOT NULL ,send_time INTEGER NOT NULL);\");\r\n }\r\n\r\n @Override\r\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n\r\n }\r\n\r\n public long insertVideoHistoryComment(VideoHistoryComment comment){\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n if (comment.anchorComment != null) {\r\n v.put(\"anchor_comment_id\", comment.anchorComment.commentId);\r\n v.put(\"anchor_comment_text\", comment.anchorComment.commentText);\r\n }\r\n v.put(\"video_id\", comment.videoId);\r\n v.put(\"state\", comment.state);\r\n v.put(\"send_date\", comment.sendDate.getTime());\r\n if (comment.repliedComment != null) {\r\n v.put(\"replied_comment_id\", comment.repliedComment.commentId);\r\n v.put(\"replied_comment_text\", comment.repliedComment.commentText);\r\n }\r\n return db.insert(TABLE_NAME_VIDEO_HISTORY_COMMENTS,null,v);\r\n }\r\n\r\n @SuppressLint(\"Range\")\r\n public List<VideoHistoryComment> queryAllVideoHistoryComments(){\r\n List<VideoHistoryComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"anchor_comment_id\", \"anchor_comment_text\", \"video_id\", \"state\", \"send_date\", \"replied_comment_id\", \"replied_comment_text\"};\r\n Cursor cursor = db.query(\"history_comments_from_video\", columns, null, null, null, null, null);\r\n\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String anchorCommentId = cursor.getString(cursor.getColumnIndex(\"anchor_comment_id\"));\r\n String anchorCommentText = cursor.getString(cursor.getColumnIndex(\"anchor_comment_text\"));\r\n String videoId = cursor.getString(cursor.getColumnIndex(\"video_id\"));\r\n String state = cursor.getString(cursor.getColumnIndex(\"state\"));\r\n long sendDate = cursor.getLong(cursor.getColumnIndex(\"send_date\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n VideoHistoryComment comment = new VideoHistoryComment(commentId, commentText, anchorCommentId, anchorCommentText, videoId, state, sendDate, repliedCommentId, repliedCommentText);\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteVideoHistoryComment(String commentId) {\r\n return db.delete(TABLE_NAME_VIDEO_HISTORY_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n public void insertToBeCheckedComment(ToBeCheckedComment comment) {\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n v.put(\"source_id\", comment.sourceId);\r\n v.put(\"comment_section_type\", comment.commentSectionType);\r\n v.put(\"replied_comment_id\", comment.repliedCommentId);\r\n v.put(\"replied_comment_text\", comment.repliedCommentText);\r\n v.put(\"context1\", comment.context1);\r\n v.put(\"send_time\",comment.sendTime.getTime());\r\n db.insert(TABLE_NAME_TO_BE_CHECKED_COMMENTS, null, v);\r\n }\r\n @SuppressLint(\"Range\")\r\n public List<ToBeCheckedComment> getAllToBeCheckedComments() {\r\n List<ToBeCheckedComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"source_id\", \"comment_section_type\", \"replied_comment_id\", \"replied_comment_text\", \"context1\",\"send_time\"};\r\n Cursor cursor = db.query(\"to_be_checked_comments\", columns, null, null, null, null, null);\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String sourceId = cursor.getString(cursor.getColumnIndex(\"source_id\"));\r\n int commentSectionType = cursor.getInt(cursor.getColumnIndex(\"comment_section_type\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n byte[] context1 = cursor.getBlob(cursor.getColumnIndex(\"context1\"));\r\n long sendTime = cursor.getLong(cursor.getColumnIndex(\"send_time\"));\r\n ToBeCheckedComment comment = new ToBeCheckedComment(commentId, commentText, sourceId, commentSectionType, repliedCommentId, repliedCommentText, context1,new Date(sendTime));\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteToBeCheckedComment(String commentId){\r\n return db.delete(TABLE_NAME_TO_BE_CHECKED_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n}\r" }, { "identifier": "ProgressBarDialog", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/ProgressBarDialog.java", "snippet": "public class ProgressBarDialog implements DialogInterface {\r\n public static final int DEFAULT_MAX_PROGRESS = 1000;\r\n public final AlertDialog alertDialog;\r\n final ProgressBar progressBar;\r\n\r\n ProgressBarDialog(AlertDialog alertDialog, ProgressBar progressBar) {\r\n this.alertDialog = alertDialog;\r\n this.progressBar = progressBar;\r\n }\r\n\r\n public void setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n }\r\n\r\n public void setMax(int max){\r\n progressBar.setMax(max);\r\n }\r\n\r\n public void setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n }\r\n\r\n public void setMessage(String message){\r\n alertDialog.setMessage(message);\r\n }\r\n\r\n public void setTitle(String title){\r\n alertDialog.setTitle(title);\r\n }\r\n\r\n public Button getButton(int whichButton){\r\n return alertDialog.getButton(whichButton);\r\n }\r\n\r\n @Override\r\n public void cancel() {\r\n alertDialog.cancel();\r\n }\r\n\r\n @Override\r\n public void dismiss() {\r\n alertDialog.dismiss();\r\n }\r\n\r\n public static class Builder {\r\n\r\n private final AlertDialog.Builder dialogBuilder;\r\n private final ProgressBar progressBar;\r\n\r\n\r\n public Builder(Context context) {\r\n dialogBuilder = new AlertDialog.Builder(context);\r\n View view = View.inflate(context, R.layout.dialog_wait_progress,null);\r\n progressBar = view.findViewById(R.id.wait_progress_bar);\r\n dialogBuilder.setView(view);\r\n progressBar.setMax(DEFAULT_MAX_PROGRESS);\r\n }\r\n\r\n public Builder setTitle(String title) {\r\n dialogBuilder.setTitle(title);\r\n return this;\r\n }\r\n\r\n public Builder setMessage(String message) {\r\n dialogBuilder.setMessage(message);\r\n return this;\r\n }\r\n\r\n public Builder setPositiveButton(String text, OnClickListener listener) {\r\n dialogBuilder.setPositiveButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNegativeButton(String text, OnClickListener listener) {\r\n dialogBuilder.setNegativeButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNeutralButton (String text, OnClickListener listener){\r\n dialogBuilder.setNeutralButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setCancelable(boolean cancelable) {\r\n dialogBuilder.setCancelable(cancelable);\r\n return this;\r\n }\r\n\r\n public Builder setOnCancelListener(OnCancelListener listener) {\r\n dialogBuilder.setOnCancelListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setOnDismissListener(OnDismissListener listener) {\r\n dialogBuilder.setOnDismissListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n return this;\r\n }\r\n\r\n public Builder setMax(int max){\r\n progressBar.setMax(max);\r\n return this;\r\n }\r\n\r\n public Builder setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n return this;\r\n }\r\n\r\n public ProgressBarDialog show() {\r\n return new ProgressBarDialog(dialogBuilder.show(),progressBar);\r\n }\r\n }\r\n\r\n\r\n}\r" }, { "identifier": "ProgressTimer", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/ProgressTimer.java", "snippet": "public class ProgressTimer {\r\n\r\n private final long TimeMs;\r\n private final int max;\r\n private final ProgressLister progressLister;\r\n\r\n private boolean isStopped = false;\r\n\r\n public ProgressTimer(long timeMs, int max, ProgressLister progressLister) {\r\n TimeMs = timeMs;\r\n this.max = max;\r\n this.progressLister = progressLister;\r\n }\r\n\r\n public void start() {\r\n long sleepSeg = TimeMs / max;\r\n for (int i = 0; i <= max && !isStopped; i++) {\r\n try {\r\n Thread.sleep(sleepSeg);\r\n progressLister.onNewProgress(i,sleepSeg);\r\n } catch (InterruptedException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n public void stop() {\r\n isStopped = true;\r\n }\r\n\r\n public interface ProgressLister {\r\n void onNewProgress(int progress,long sleepSeg);\r\n }\r\n}\r" } ]
import java.io.IOException; import java.util.Date; import java.util.List; import icu.freedomintrovert.YTSendCommAntiFraud.Config; import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.ToBeCheckedComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoCommentSection; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoHistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB; import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog; import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressTimer; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.ObservableEmitter; import io.reactivex.rxjava3.core.ObservableOnSubscribe;
6,225
package icu.freedomintrovert.YTSendCommAntiFraud.rxObservables; public class FindCommentObservableOnSubscribe implements ObservableOnSubscribe<FindCommentObservableOnSubscribe.BaseNextValue> { private final VideoCommentSection videoCommentSection; private VideoComment toBeCheckedComment; private final long waitTimeAfterCommentSent; private final long intervalOfSearchAgain; private final int maximumNumberOfSearchAgain; private StatisticsDB statisticsDB; private boolean needToWait; private final Date sendDate;
package icu.freedomintrovert.YTSendCommAntiFraud.rxObservables; public class FindCommentObservableOnSubscribe implements ObservableOnSubscribe<FindCommentObservableOnSubscribe.BaseNextValue> { private final VideoCommentSection videoCommentSection; private VideoComment toBeCheckedComment; private final long waitTimeAfterCommentSent; private final long intervalOfSearchAgain; private final int maximumNumberOfSearchAgain; private StatisticsDB statisticsDB; private boolean needToWait; private final Date sendDate;
private ProgressTimer progressTimer;
9
2023-10-15 01:18:28+00:00
8k
New-Barams/This-Year-Ajaja-BE
src/test/java/com/newbarams/ajaja/module/plan/domain/repository/PlanQueryRepositoryTest.java
[ { "identifier": "MonkeySupport", "path": "src/test/java/com/newbarams/ajaja/common/support/MonkeySupport.java", "snippet": "public abstract class MonkeySupport {\n\tprotected final FixtureMonkey sut = FixtureMonkey.builder()\n\t\t.objectIntrospector(new FailoverIntrospector(\n\t\t\tList.of(\n\t\t\t\tFieldReflectionArbitraryIntrospector.INSTANCE,\n\t\t\t\tConstructorPropertiesArbitraryIntrospector.INSTANCE\n\t\t\t)\n\t\t))\n\t\t.plugin(new JakartaValidationPlugin())\n\t\t.defaultNotNull(true)\n\t\t.build();\n}" }, { "identifier": "TimeValue", "path": "src/main/java/com/newbarams/ajaja/global/common/TimeValue.java", "snippet": "@Getter\npublic class TimeValue {\n\tprivate static final String DEFAULT_TIME_ZONE = \"Asia/Seoul\";\n\tprivate static final int THREE_DAYS = 3;\n\tprivate static final int LAST_MONTH = 12;\n\n\tprivate final Instant instant;\n\tprivate final ZonedDateTime zonedDateTime;\n\n\tpublic TimeValue(Instant instant) {\n\t\tthis.instant = instant;\n\t\tzonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of(DEFAULT_TIME_ZONE));\n\t}\n\n\tpublic TimeValue() {\n\t\tthis(Instant.now());\n\t}\n\n\tpublic int getYear() {\n\t\treturn zonedDateTime.getYear();\n\t}\n\n\tpublic int getMonth() {\n\t\treturn zonedDateTime.getMonthValue();\n\t}\n\n\tpublic int getDate() {\n\t\treturn zonedDateTime.getDayOfMonth();\n\t}\n\n\tpublic Date expireIn(long validTime) {\n\t\treturn new Date(instant.toEpochMilli() + validTime);\n\t}\n\n\tpublic long getTimeMillis() {\n\t\treturn instant.toEpochMilli();\n\t}\n\n\tpublic ZonedDateTime oneMonthLater() {\n\t\treturn zonedDateTime.getMonthValue() == LAST_MONTH\n\t\t\t? parseDateTime(12, 31, 23, 59) : zonedDateTime.plusMonths(1);\n\t}\n\n\tpublic boolean isWithinThreeDays(Date expireIn) {\n\t\tDuration between = Duration.between(instant, expireIn.toInstant());\n\t\treturn Math.abs(between.toDays()) <= THREE_DAYS;\n\t}\n\n\tpublic boolean isAfter(TimeValue time) {\n\t\treturn zonedDateTime.isAfter(time.zonedDateTime);\n\t}\n\n\tpublic boolean isBetween(TimeValue time) {\n\t\treturn this.zonedDateTime.isAfter(time.zonedDateTime)\n\t\t\t&& this.zonedDateTime.isBefore(time.oneMonthLater());\n\t}\n\n\tprivate ZonedDateTime parseDateTime(int month, int date, int hour, int minute) {\n\t\treturn Year.of(zonedDateTime.getYear())\n\t\t\t.atMonth(month)\n\t\t\t.atDay(date)\n\t\t\t.atTime(hour, minute)\n\t\t\t.atZone(ZoneId.of(DEFAULT_TIME_ZONE));\n\t}\n\n\tpublic boolean isExpired() {\n\t\treturn zonedDateTime.isAfter(zonedDateTime.plusMonths(1));\n\t}\n\n\tpublic static TimeValue parse(int year, int month, int date, int hour) {\n\t\tInstant instant = Year.of(year)\n\t\t\t.atMonth(month)\n\t\t\t.atDay(date)\n\t\t\t.atTime(hour, 0)\n\t\t\t.atZone(ZoneId.of(DEFAULT_TIME_ZONE))\n\t\t\t.toInstant();\n\n\t\treturn new TimeValue(instant);\n\t}\n}" }, { "identifier": "Plan", "path": "src/main/java/com/newbarams/ajaja/module/plan/domain/Plan.java", "snippet": "@Getter\n@AllArgsConstructor\npublic class Plan {\n\tprivate static final int MODIFIABLE_MONTH = 1;\n\tprivate static final int ONE_MONTH_TERM = 1;\n\n\tprivate Long id;\n\n\tprivate Long userId;\n\n\tprivate int iconNumber;\n\n\tprivate Content content;\n\tprivate RemindInfo info;\n\tprivate PlanStatus status;\n\n\tprivate List<Message> messages;\n\n\tprivate List<AjajaEntity> ajajas;\n\tprivate TimeValue createdAt;\n\n\tPlan(Long userId, Content content, RemindInfo info, PlanStatus status,\n\t\tint iconNumber, List<Message> messages) {\n\t\tthis.userId = userId;\n\t\tthis.content = content;\n\t\tthis.info = info;\n\t\tthis.status = status;\n\t\tthis.iconNumber = iconNumber;\n\t\tthis.messages = messages;\n\t\tthis.ajajas = new ArrayList<>();\n\t}\n\n\tpublic static Plan create(PlanParam.Create param) {\n\t\tvalidateModifiableMonth(param.getMonth());\n\n\t\treturn new Plan(param.getUserId(), param.getContent(), param.getInfo(), param.getStatus(),\n\t\t\tparam.getIconNumber(), param.getMessages());\n\t}\n\n\tpublic void delete(Long userId, int month) {\n\t\tvalidateModifiableMonth(month);\n\t\tvalidateUser(userId);\n\t\tthis.status.toDeleted();\n\t}\n\n\tprivate static void validateModifiableMonth(int month) {\n\t\tif (month != MODIFIABLE_MONTH) {\n\t\t\tthrow new AjajaException(INVALID_UPDATABLE_DATE);\n\t\t}\n\t}\n\n\tprivate void validateUser(Long userId) {\n\t\tif (!this.userId.equals(userId)) {\n\t\t\tthrow new AjajaException(INVALID_USER_ACCESS);\n\t\t}\n\t}\n\n\tpublic void updatePublicStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchPublic();\n\t}\n\n\tpublic void updateRemindStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchRemind();\n\t}\n\n\tpublic void updateAjajaStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchAjaja();\n\t}\n\n\tpublic void update(PlanParam.Update param) {\n\t\tvalidateModifiableMonth(param.getMonth());\n\t\tvalidateUser(param.getUserId());\n\t\tthis.iconNumber = param.getIconNumber();\n\t\tthis.content = param.getContent();\n\t\tthis.status = status.update(param.isPublic(), param.isCanAjaja());\n\t}\n\n\tpublic void updateRemind(RemindInfo info, List<Message> messages) {\n\t\tif (new TimeValue().getMonth() != MODIFIABLE_MONTH) {\n\t\t\tthrow new AjajaException(INVALID_UPDATABLE_DATE);\n\t\t}\n\n\t\tthis.info = info;\n\t\tthis.messages = messages;\n\t}\n\n\tpublic int getRemindTime() {\n\t\treturn this.info.getRemindTime();\n\t}\n\n\tpublic String getRemindTimeName() {\n\t\treturn this.info.getRemindTimeName();\n\t}\n\n\tpublic int getRemindMonth() {\n\t\treturn this.info.getRemindMonth();\n\t}\n\n\tpublic int getRemindDate() {\n\t\treturn this.info.getRemindDate();\n\t}\n\n\tpublic int getRemindTerm() {\n\t\treturn this.info.getRemindTerm();\n\t}\n\n\tpublic int getRemindTotalPeriod() {\n\t\treturn this.info.getRemindTotalPeriod();\n\t}\n\n\tpublic boolean getIsRemindable() {\n\t\treturn this.status.isCanRemind();\n\t}\n\n\tpublic int getTotalRemindNumber() {\n\t\treturn this.info.getTotalRemindNumber();\n\t}\n\n\tpublic String getPlanTitle() {\n\t\treturn this.content.getTitle();\n\t}\n\n\tpublic String getMessage(int currentMonth) {\n\t\tint messageIdx = getMessageIdx(this.info.getRemindTerm(), currentMonth);\n\t\treturn this.messages.get(messageIdx).getContent();\n\t}\n\n\tprivate int getMessageIdx(int remindTerm, int currentMonth) {\n\t\treturn remindTerm == ONE_MONTH_TERM ? (currentMonth - 2) : currentMonth / remindTerm - 1;\n\t}\n\n\tpublic void disable() {\n\t\tthis.status = status.disable();\n\t}\n\n\tpublic TimeValue getFeedbackPeriod(TimeValue current) {\n\t\treturn this.messages.stream()\n\t\t\t.filter(message -> current.isBetween(\n\t\t\t\tTimeValue.parse(\n\t\t\t\t\tthis.createdAt.getYear(),\n\t\t\t\t\tmessage.getRemindDate().getRemindMonth(),\n\t\t\t\t\tmessage.getRemindDate().getRemindDay(),\n\t\t\t\t\tthis.getRemindTime()))\n\t\t\t)\n\t\t\t.findAny()\n\t\t\t.map(message -> TimeValue.parse(this.createdAt.getYear(),\n\t\t\t\tmessage.getRemindDate().getRemindMonth(),\n\t\t\t\tmessage.getRemindDate().getRemindDay(),\n\t\t\t\tthis.getRemindTime()))\n\t\t\t.orElseThrow(() -> new AjajaException(EXPIRED_FEEDBACK));\n\t}\n}" }, { "identifier": "PlanRepository", "path": "src/main/java/com/newbarams/ajaja/module/plan/domain/PlanRepository.java", "snippet": "@Repository\npublic interface PlanRepository {\n\tPlan save(Plan plan);\n\n\tOptional<Plan> findById(Long id);\n\n\tList<Plan> saveAll(List<Plan> plans);\n}" }, { "identifier": "PlanStatus", "path": "src/main/java/com/newbarams/ajaja/module/plan/domain/PlanStatus.java", "snippet": "@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor\npublic class PlanStatus {\n\tprivate boolean isPublic;\n\tprivate boolean canRemind;\n\tprivate boolean canAjaja;\n\tprivate boolean deleted;\n\n\tpublic PlanStatus(boolean isPublic, boolean canAjaja) {\n\t\tthis(isPublic, true, canAjaja, false);\n\t}\n\n\tvoid toDeleted() {\n\t\tthis.deleted = true;\n\t}\n\n\tvoid switchPublic() {\n\t\tthis.isPublic = !isPublic;\n\t}\n\n\tvoid switchRemind() {\n\t\tthis.canRemind = !canRemind;\n\t}\n\n\tvoid switchAjaja() {\n\t\tthis.canAjaja = !canAjaja;\n\t}\n\n\tPlanStatus disable() {\n\t\treturn new PlanStatus(isPublic, false, false, true);\n\t}\n\n\tPlanStatus update(boolean isPublic, boolean canAjaja) {\n\t\treturn new PlanStatus(isPublic, canRemind, canAjaja, deleted);\n\t}\n}" }, { "identifier": "PlanRequest", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanRequest.java", "snippet": "public class PlanRequest {\n\t@Data\n\tpublic static class Create {\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int remindTotalPeriod;\n\t\tprivate final int remindTerm;\n\t\tprivate final int remindDate;\n\t\tprivate final String remindTime;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final List<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class Message {\n\t\tprivate final String content;\n\t\tprivate final int remindMonth;\n\t\tprivate final int remindDay;\n\t}\n\n\t@Data\n\tpublic static class Update {\n\t\tprivate final int iconNumber;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class UpdateRemind {\n\t\tint remindTotalPeriod;\n\t\tint remindTerm;\n\t\tint remindDate;\n\t\tString remindTime;\n\t\tList<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final String sort;\n\t\tprivate final boolean current;\n\t\tprivate final Integer ajaja;\n\t\tprivate final Long start;\n\t}\n}" }, { "identifier": "PlanResponse", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanResponse.java", "snippet": "public final class PlanResponse {\n\t@Data\n\tpublic static class Detail {\n\t\tprivate final Writer writer;\n\t\tprivate final Long id;\n\t\tprivate final String title;\n\t\tprivate final String description;\n\t\tprivate final int icon;\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\t\tprivate final long ajajas;\n\t\tprivate final List<String> tags;\n\t\tprivate final Instant createdAt;\n\n\t\t@QueryProjection\n\t\tpublic Detail(Writer writer, Long id, String title, String description, int icon, boolean isPublic,\n\t\t\tboolean canRemind, boolean canAjaja, long ajajas, List<String> tags, Instant createdAt\n\t\t) {\n\t\t\tthis.writer = writer;\n\t\t\tthis.id = id;\n\t\t\tthis.title = title;\n\t\t\tthis.description = description;\n\t\t\tthis.icon = icon;\n\t\t\tthis.isPublic = isPublic;\n\t\t\tthis.canRemind = canRemind;\n\t\t\tthis.canAjaja = canAjaja;\n\t\t\tthis.ajajas = ajajas;\n\t\t\tthis.tags = tags;\n\t\t\tthis.createdAt = createdAt;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class Writer {\n\t\tprivate final String nickname;\n\t\tprivate final boolean isOwner;\n\t\tprivate final boolean isAjajaPressed;\n\n\t\t@QueryProjection\n\t\tpublic Writer(String nickname, boolean isOwner, boolean isAjajaPressed) {\n\t\t\tthis.nickname = nickname;\n\t\t\tthis.isOwner = isOwner;\n\t\t\tthis.isAjajaPressed = isAjajaPressed;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class GetOne {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final long ajajas;\n\t\tprivate final boolean isPressAjaja;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final long ajajas;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class Create {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int ajajas = 0;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class MainInfo {\n\t\tprivate final int year;\n\t\tprivate final int totalAchieveRate;\n\t\tprivate final List<PlanResponse.PlanInfo> getPlanList;\n\t}\n\n\t@Data\n\tpublic static class PlanInfo {\n\t\tprivate final int year;\n\t\tprivate final Long planId;\n\t\tprivate final String title;\n\t\tprivate final boolean remindable;\n\t\tprivate final int achieveRate;\n\t\tprivate final int icon;\n\t}\n}" }, { "identifier": "PlanQueryRepository", "path": "src/main/java/com/newbarams/ajaja/module/plan/infra/PlanQueryRepository.java", "snippet": "@Repository\n@RequiredArgsConstructor\npublic class PlanQueryRepository {\n\tprivate static final String LATEST = \"latest\";\n\tprivate static final String AJAJA = \"ajaja\";\n\tprivate static final int PAGE_SIZE = 3;\n\n\tprivate final JPAQueryFactory queryFactory;\n\tprivate final PlanMapper planMapper;\n\n\tpublic List<Plan> findAllCurrentPlansByUserId(Long userId) { // todo: domain dependency\n\t\treturn queryFactory.selectFrom(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(isCurrentYear()))\n\t\t\t.fetch()\n\t\t\t.stream().map(planMapper::toDomain)\n\t\t\t.toList();\n\t}\n\n\tpublic Long countByUserId(Long userId) {\n\t\treturn queryFactory.select(planEntity.count())\n\t\t\t.from(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(isCurrentYear()))\n\t\t\t.fetchFirst();\n\t}\n\n\tprivate BooleanExpression isCurrentYear() {\n\t\treturn planEntity.createdAt.year().eq(new TimeValue().getYear());\n\t}\n\n\tpublic Optional<PlanResponse.Detail> findPlanDetailByIdAndOptionalUser(Long userId, Long id) {\n\t\treturn Optional.ofNullable(queryFactory.select(new QPlanResponse_Detail(\n\t\t\t\tnew QPlanResponse_Writer(\n\t\t\t\t\tuserEntity.nickname,\n\t\t\t\t\tuserId == null ? FALSE : userEntity.id.intValue().eq(asNumber(userId)), // bigint casting error\n\t\t\t\t\tuserId == null ? FALSE : isAjajaPressed(userId, id)),\n\t\t\t\tasNumber(id),\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.description,\n\t\t\t\tplanEntity.iconNumber,\n\t\t\t\tplanEntity.isPublic,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tplanEntity.canAjaja,\n\t\t\t\tplanEntity.ajajas.size().longValue(),\n\t\t\t\tconstant(findAllTagsByPlanId(id)),\n\t\t\t\tplanEntity.createdAt))\n\t\t\t.from(planEntity)\n\t\t\t.leftJoin(userEntity).on(userEntity.id.eq(planEntity.userId))\n\t\t\t.where(planEntity.id.eq(id))\n\t\t\t.fetchOne()\n\t\t);\n\t}\n\n\tprivate BooleanExpression isAjajaPressed(Long userId, Long id) {\n\t\treturn Expressions.asBoolean(queryFactory.selectFrom(ajajaEntity)\n\t\t\t.where(ajajaEntity.targetId.eq(id)\n\t\t\t\t.and(ajajaEntity.userId.eq(userId))\n\t\t\t\t.and(ajajaEntity.type.eq(Ajaja.Type.PLAN.name()))\n\t\t\t\t.and(ajajaEntity.canceled.isFalse()))\n\t\t\t.fetchFirst() != null);\n\t}\n\n\tpublic Plan findByUserIdAndPlanId(Long userId, Long planId) {\n\t\tPlanEntity entity = queryFactory.selectFrom(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(planEntity.id.eq(planId)))\n\t\t\t.fetchOne();\n\n\t\tif (entity == null) {\n\t\t\tthrow AjajaException.withId(planId, NOT_FOUND_PLAN);\n\t\t}\n\t\treturn planMapper.toDomain(entity);\n\t}\n\n\tprivate List<String> findAllTagsByPlanId(Long planId) {\n\t\treturn queryFactory.select(tag.name)\n\t\t\t.from(planTag, tag)\n\t\t\t.where(planTag.tagId.eq(tag.id)\n\t\t\t\t.and(planTag.planId.eq(planId)))\n\t\t\t.fetch();\n\t}\n\n\tpublic List<PlanResponse.GetAll> findAllByCursorAndSorting(PlanRequest.GetAll conditions) {\n\t\tList<Tuple> tuples = queryFactory.select(planEntity, userEntity.nickname)\n\t\t\t.from(planEntity, userEntity)\n\n\t\t\t.where(planEntity.userId.eq(userEntity.id),\n\t\t\t\tplanEntity.isPublic.eq(true),\n\t\t\t\tisEqualsYear(conditions.isCurrent()),\n\t\t\t\tcursorPagination(conditions))\n\n\t\t\t.orderBy(sortBy(conditions.getSort()))\n\t\t\t.limit(PAGE_SIZE)\n\t\t\t.fetch();\n\n\t\treturn tupleToResponse(tuples);\n\t}\n\n\tprivate BooleanExpression isEqualsYear(boolean isNewYear) {\n\t\tint currentYear = new TimeValue().getYear();\n\t\treturn isNewYear ? planEntity.createdAt.year().eq(currentYear) : planEntity.createdAt.year().ne(currentYear);\n\t}\n\n\tprivate BooleanExpression cursorPagination(PlanRequest.GetAll conditions) {\n\t\treturn conditions.getStart() == null ? null :\n\t\t\tgetCursorCondition(conditions.getSort(), conditions.getStart(), conditions.getAjaja());\n\t}\n\n\tprivate BooleanExpression getCursorCondition(String sort, Long start, Integer cursorAjaja) {\n\t\treturn sort.equalsIgnoreCase(LATEST) ? planEntity.id.lt(start) : cursorAjajaAndId(cursorAjaja, start);\n\t}\n\n\tprivate BooleanExpression cursorAjajaAndId(Integer cursorAjaja, Long cursorId) {\n\t\treturn cursorAjaja == null ? null :\n\t\t\tplanEntity.ajajas.size().eq(cursorAjaja)\n\t\t\t\t.and(planEntity.id.lt(cursorId))\n\t\t\t\t.or(planEntity.ajajas.size().lt(cursorAjaja));\n\t}\n\n\tprivate OrderSpecifier[] sortBy(String condition) {\n\t\treturn switch (condition.toLowerCase(Locale.ROOT)) {\n\t\t\tcase LATEST -> new OrderSpecifier[] {new OrderSpecifier<>(Order.DESC, planEntity.createdAt)};\n\t\t\tcase AJAJA -> new OrderSpecifier[] {\n\t\t\t\tnew OrderSpecifier<>(Order.DESC, planEntity.ajajas.size()),\n\t\t\t\tnew OrderSpecifier<>(Order.DESC, planEntity.id)\n\t\t\t};\n\t\t\tdefault -> new OrderSpecifier[0];\n\t\t};\n\t}\n\n\tprivate List<PlanResponse.GetAll> tupleToResponse(List<Tuple> tuples) {\n\t\treturn tuples.stream()\n\t\t\t.map(tuple -> {\n\t\t\t\tPlanEntity planFromTuple = tuple.get(planEntity);\n\t\t\t\tString nickname = tuple.get(userEntity.nickname);\n\t\t\t\tList<String> tags = findAllTagsByPlanId(planFromTuple.getId());\n\n\t\t\t\treturn planMapper.toResponse(planFromTuple, nickname, tags);\n\t\t\t})\n\t\t\t.toList();\n\t}\n\n\tpublic List<PlanResponse.PlanInfo> findAllPlanByUserId(Long userId) {\n\t\treturn queryFactory.select(Projections.constructor(PlanResponse.PlanInfo.class,\n\t\t\t\tplanEntity.createdAt.year(),\n\t\t\t\tplanEntity.id,\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tfeedbackEntity.achieve.avg().intValue(),\n\t\t\t\tplanEntity.iconNumber\n\t\t\t))\n\t\t\t.from(planEntity)\n\t\t\t.leftJoin(feedbackEntity).on(feedbackEntity.planId.eq(planEntity.id))\n\t\t\t.groupBy(planEntity.createdAt.year(),\n\t\t\t\tplanEntity.id,\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tplanEntity.iconNumber)\n\t\t\t.where(planEntity.userId.eq(userId))\n\t\t\t.orderBy(planEntity.createdAt.year().desc())\n\t\t\t.fetch();\n\t}\n\n\tpublic List<RemindMessageInfo> findAllRemindablePlan(String remindTime, TimeValue time) {\n\t\treturn queryFactory.select(planEntity, userEntity.remindEmail)\n\t\t\t.from(planEntity)\n\t\t\t.join(userEntity).on(userEntity.id.eq(planEntity.userId))\n\t\t\t.where(planEntity.canRemind\n\t\t\t\t.and(planEntity.remindTime.eq(remindTime).and(isRemindable(time))))\n\t\t\t.fetch().stream()\n\t\t\t.map(t -> planMapper.toModel(t.get(planEntity), t.get(userEntity.remindEmail)))\n\t\t\t.toList();\n\t}\n\n\tprivate BooleanExpression isRemindable(TimeValue time) {\n\t\tRemindDate today = new RemindDate(time.getMonth(), time.getDate());\n\t\treturn planEntity.createdAt.year().eq(time.getYear())\n\t\t\t.andAnyOf(planEntity.messages.any().remindDate.eq(today));\n\t}\n}" }, { "identifier": "UserJpaRepository", "path": "src/main/java/com/newbarams/ajaja/module/user/adapter/out/persistence/UserJpaRepository.java", "snippet": "public interface UserJpaRepository extends JpaRepository<UserEntity, Long> {\n\tOptional<UserEntity> findBySignUpEmail(String email);\n\n\tboolean existsById(Long id);\n}" }, { "identifier": "UserEntity", "path": "src/main/java/com/newbarams/ajaja/module/user/adapter/out/persistence/model/UserEntity.java", "snippet": "@Getter\n@Entity\n@Table(name = \"users\")\n@Where(clause = \"deleted = false\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor\npublic class UserEntity extends BaseEntity<UserEntity> {\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"user_id\")\n\tprivate Long id;\n\n\t@Column(nullable = false, length = 20)\n\tprivate String nickname;\n\n\t@Column(nullable = false, name = \"email\", length = 50)\n\tprivate String signUpEmail;\n\n\t@Column(nullable = false, length = 50)\n\tprivate String remindEmail;\n\n\t@Column(nullable = false)\n\tprivate boolean verified;\n\n\t@Column(nullable = false, length = 20)\n\tprivate String receiveType;\n\n\t@Embedded\n\tprivate OauthInfo oauthInfo;\n\n\t@Column(nullable = false)\n\tprivate boolean deleted;\n}" }, { "identifier": "User", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/User.java", "snippet": "@Getter\n@AllArgsConstructor\npublic class User {\n\tpublic enum ReceiveType {\n\t\tKAKAO, EMAIL, BOTH\n\t}\n\n\tprivate final UserId userId;\n\tprivate Nickname nickname;\n\tprivate Email email;\n\tprivate ReceiveType receiveType;\n\tprivate boolean deleted;\n\n\tpublic static User init(String email, Long oauthId) {\n\t\treturn new User(UserId.from(oauthId), Nickname.renew(), new Email(email), ReceiveType.KAKAO, false);\n\t}\n\n\tpublic void delete() {\n\t\tthis.deleted = true;\n\t}\n\n\tpublic void validateEmail(String requestEmail) {\n\t\temail.validateVerifiable(requestEmail);\n\t}\n\n\tpublic void verified(String validatedEmail) {\n\t\tthis.email = email.verified(validatedEmail);\n\t}\n\n\tpublic void updateNickname() {\n\t\tthis.nickname = Nickname.renew();\n\t}\n\n\tpublic void updateReceive(ReceiveType receiveType) {\n\t\tthis.receiveType = receiveType;\n\t}\n\n\tpublic Long getId() {\n\t\treturn userId.getId();\n\t}\n\n\tpublic Long getOauthId() {\n\t\treturn userId.getOauthId();\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email.getSignUpEmail();\n\t}\n\n\tpublic String getRemindEmail() {\n\t\treturn email.getRemindEmail();\n\t}\n\n\tpublic boolean isVerified() {\n\t\treturn email.isVerified();\n\t}\n}" }, { "identifier": "UserMapper", "path": "src/main/java/com/newbarams/ajaja/module/user/mapper/UserMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserMapper {\n\t@Mapping(source = \"userEntity\", target = \"userId\", qualifiedByName = \"toUserId\")\n\t@Mapping(target = \"nickname\", expression = \"java(new Nickname(userEntity.getNickname()))\")\n\t@Mapping(source = \"userEntity\", target = \"email\", qualifiedByName = \"toEmail\")\n\tUser toDomain(UserEntity userEntity);\n\n\t@Named(\"toUserId\")\n\tstatic UserId toUserId(UserEntity userEntity) {\n\t\treturn new UserId(userEntity.getId(), userEntity.getOauthInfo().getOauthId());\n\t}\n\n\t@Named(\"toEmail\")\n\tstatic Email toEmail(UserEntity userEntity) {\n\t\treturn new Email(userEntity.getSignUpEmail(), userEntity.getRemindEmail(), userEntity.isVerified());\n\t}\n\n\t@Mapping(source = \"userId.id\", target = \"id\")\n\t@Mapping(source = \"nickname.nickname\", target = \"nickname\")\n\t@Mapping(target = \"signUpEmail\", expression = \"java(user.getEmail())\") // getter overrided\n\t@Mapping(target = \"remindEmail\", expression = \"java(user.getRemindEmail())\") // getter overrided\n\t@Mapping(target = \"verified\", expression = \"java(user.isVerified())\") // getter overrided\n\t@Mapping(target = \"oauthInfo\", expression = \"java(OauthInfo.kakao(user.getOauthId()))\")\n\tUserEntity toEntity(User user);\n}" } ]
import static org.assertj.core.api.Assertions.*; import java.util.Collections; import java.util.List; import java.util.Optional; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import com.newbarams.ajaja.common.support.MonkeySupport; import com.newbarams.ajaja.global.common.TimeValue; import com.newbarams.ajaja.module.plan.domain.Plan; import com.newbarams.ajaja.module.plan.domain.PlanRepository; import com.newbarams.ajaja.module.plan.domain.PlanStatus; import com.newbarams.ajaja.module.plan.dto.PlanRequest; import com.newbarams.ajaja.module.plan.dto.PlanResponse; import com.newbarams.ajaja.module.plan.infra.PlanQueryRepository; import com.newbarams.ajaja.module.user.adapter.out.persistence.UserJpaRepository; import com.newbarams.ajaja.module.user.adapter.out.persistence.model.UserEntity; import com.newbarams.ajaja.module.user.domain.User; import com.newbarams.ajaja.module.user.mapper.UserMapper;
6,676
package com.newbarams.ajaja.module.plan.domain.repository; @SpringBootTest @Transactional class PlanQueryRepositoryTest extends MonkeySupport { @Autowired private PlanQueryRepository planQueryRepository; @Autowired private PlanRepository planRepository; @Autowired private UserJpaRepository userRepository; @Autowired private UserMapper userMapper; private User user;
package com.newbarams.ajaja.module.plan.domain.repository; @SpringBootTest @Transactional class PlanQueryRepositoryTest extends MonkeySupport { @Autowired private PlanQueryRepository planQueryRepository; @Autowired private PlanRepository planRepository; @Autowired private UserJpaRepository userRepository; @Autowired private UserMapper userMapper; private User user;
private Plan plan;
2
2023-10-23 07:24:17+00:00
8k
eclipse-jgit/jgit
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/diffmergetool/ExternalMergeToolTest.java
[ { "identifier": "CONFIG_KEY_CMD", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_CMD = \"cmd\";" }, { "identifier": "CONFIG_KEY_GUITOOL", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_GUITOOL = \"guitool\";" }, { "identifier": "CONFIG_KEY_PATH", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_PATH = \"path\";" }, { "identifier": "CONFIG_KEY_PROMPT", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_PROMPT = \"prompt\";" }, { "identifier": "CONFIG_KEY_TOOL", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_TOOL = \"tool\";" }, { "identifier": "CONFIG_KEY_TRUST_EXIT_CODE", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_TRUST_EXIT_CODE = \"trustExitCode\";" }, { "identifier": "CONFIG_MERGETOOL_SECTION", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_MERGETOOL_SECTION = \"mergetool\";" }, { "identifier": "CONFIG_MERGE_SECTION", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_MERGE_SECTION = \"merge\";" }, { "identifier": "BooleanTriState", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/internal/BooleanTriState.java", "snippet": "public enum BooleanTriState {\n\t/**\n\t * Value equivalent to {@code true}.\n\t */\n\tTRUE,\n\t/**\n\t * Value equivalent to {@code false}.\n\t */\n\tFALSE,\n\t/**\n\t * Value is not set.\n\t */\n\tUNSET;\n}" }, { "identifier": "FileBasedConfig", "path": "org.eclipse.jgit/src/org/eclipse/jgit/storage/file/FileBasedConfig.java", "snippet": "public class FileBasedConfig extends StoredConfig {\n\n\tprivate final File configFile;\n\n\tprivate final FS fs;\n\n\t// In-process synchronization between load() and save().\n\tprivate final ReentrantReadWriteLock lock;\n\n\tprivate boolean utf8Bom;\n\n\tprivate volatile FileSnapshot snapshot;\n\n\tprivate volatile ObjectId hash;\n\n\tprivate AtomicBoolean exists = new AtomicBoolean();\n\n\n\t/**\n\t * Create a configuration with no default fallback.\n\t *\n\t * @param cfgLocation\n\t * the location of the configuration file on the file system\n\t * @param fs\n\t * the file system abstraction which will be necessary to perform\n\t * certain file system operations.\n\t */\n\tpublic FileBasedConfig(File cfgLocation, FS fs) {\n\t\tthis(null, cfgLocation, fs);\n\t}\n\n\t/**\n\t * The constructor\n\t *\n\t * @param base\n\t * the base configuration file\n\t * @param cfgLocation\n\t * the location of the configuration file on the file system\n\t * @param fs\n\t * the file system abstraction which will be necessary to perform\n\t * certain file system operations.\n\t */\n\tpublic FileBasedConfig(Config base, File cfgLocation, FS fs) {\n\t\tsuper(base);\n\t\tconfigFile = cfgLocation;\n\t\tthis.fs = fs;\n\t\tthis.snapshot = FileSnapshot.DIRTY;\n\t\tthis.hash = ObjectId.zeroId();\n\t\tthis.lock = new ReentrantReadWriteLock(false);\n\t}\n\n\t@Override\n\tprotected boolean notifyUponTransientChanges() {\n\t\t// we will notify listeners upon save()\n\t\treturn false;\n\t}\n\n\t/**\n\t * Get location of the configuration file on disk\n\t *\n\t * @return location of the configuration file on disk\n\t */\n\tpublic final File getFile() {\n\t\treturn configFile;\n\t}\n\n\tboolean exists() {\n\t\treturn exists.get();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * <p>\n\t * Load the configuration as a Git text style configuration file.\n\t * <p>\n\t * If the file does not exist, this configuration is cleared, and thus\n\t * behaves the same as though the file exists, but is empty.\n\t */\n\t@Override\n\tpublic void load() throws IOException, ConfigInvalidException {\n\t\tlock.readLock().lock();\n\t\ttry {\n\t\t\tBoolean wasRead = FileUtils.readWithRetries(getFile(), this::load);\n\t\t\tif (wasRead == null) {\n\t\t\t\tclear();\n\t\t\t\tsnapshot = FileSnapshot.MISSING_FILE;\n\t\t\t}\n\t\t\texists.set(wasRead != null);\n\t\t} catch (IOException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow new ConfigInvalidException(MessageFormat\n\t\t\t\t\t.format(JGitText.get().cannotReadFile, getFile()), e);\n\t\t} finally {\n\t\t\tlock.readLock().unlock();\n\t\t}\n\t}\n\n\tprivate Boolean load(File f) throws Exception {\n\t\tFileSnapshot oldSnapshot = snapshot;\n\t\t// don't use config in this snapshot to avoid endless recursion\n\t\tFileSnapshot newSnapshot = FileSnapshot.saveNoConfig(f);\n\t\tbyte[] in = IO.readFully(f);\n\t\tObjectId newHash = hash(in);\n\t\tif (hash.equals(newHash)) {\n\t\t\tif (oldSnapshot.equals(newSnapshot)) {\n\t\t\t\toldSnapshot.setClean(newSnapshot);\n\t\t\t} else {\n\t\t\t\tsnapshot = newSnapshot;\n\t\t\t}\n\t\t} else {\n\t\t\tString decoded;\n\t\t\tif (isUtf8(in)) {\n\t\t\t\tdecoded = RawParseUtils.decode(UTF_8, in, 3, in.length);\n\t\t\t\tutf8Bom = true;\n\t\t\t} else {\n\t\t\t\tdecoded = RawParseUtils.decode(in);\n\t\t\t}\n\t\t\tfromText(decoded);\n\t\t\tsnapshot = newSnapshot;\n\t\t\thash = newHash;\n\t\t}\n\t\treturn Boolean.TRUE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * <p>\n\t * Save the configuration as a Git text style configuration file.\n\t * <p>\n\t * <b>Warning:</b> Although this method uses the traditional Git file\n\t * locking approach to protect against concurrent writes of the\n\t * configuration file, it does not ensure that the file has not been\n\t * modified since the last read, which means updates performed by other\n\t * objects accessing the same backing file may be lost.\n\t */\n\t@Override\n\tpublic void save() throws IOException {\n\t\tlock.writeLock().lock();\n\t\ttry {\n\t\t\tbyte[] out;\n\t\t\tString text = toText();\n\t\t\tif (utf8Bom) {\n\t\t\t\tfinal ByteArrayOutputStream bos = new ByteArrayOutputStream();\n\t\t\t\tbos.write(0xEF);\n\t\t\t\tbos.write(0xBB);\n\t\t\t\tbos.write(0xBF);\n\t\t\t\tbos.write(text.getBytes(UTF_8));\n\t\t\t\tout = bos.toByteArray();\n\t\t\t} else {\n\t\t\t\tout = Constants.encode(text);\n\t\t\t}\n\n\t\t\tLockFile lf = new LockFile(getFile());\n\t\t\ttry {\n\t\t\t\tif (!lf.lock()) {\n\t\t\t\t\tthrow new LockFailedException(getFile());\n\t\t\t\t}\n\t\t\t\tlf.setNeedSnapshotNoConfig(true);\n\t\t\t\tlf.write(out);\n\t\t\t\tif (!lf.commit()) {\n\t\t\t\t\tthrow new IOException(MessageFormat.format(\n\t\t\t\t\t\t\tJGitText.get().cannotCommitWriteTo, getFile()));\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tlf.unlock();\n\t\t\t}\n\t\t\tsnapshot = lf.getCommitSnapshot();\n\t\t\thash = hash(out);\n\t\t\texists.set(true);\n\t\t} finally {\n\t\t\tlock.writeLock().unlock();\n\t\t}\n\t\t// notify the listeners\n\t\tfireConfigChangedEvent();\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\thash = hash(new byte[0]);\n\t\tsuper.clear();\n\t}\n\n\tprivate static ObjectId hash(byte[] rawText) {\n\t\treturn ObjectId.fromRaw(Constants.newMessageDigest().digest(rawText));\n\t}\n\n\t@SuppressWarnings(\"nls\")\n\t@Override\n\tpublic String toString() {\n\t\treturn getClass().getSimpleName() + \"[\" + getFile().getPath() + \"]\";\n\t}\n\n\t/**\n\t * Whether the currently loaded configuration file is outdated\n\t *\n\t * @return returns true if the currently loaded configuration file is older\n\t * than the file on disk\n\t */\n\tpublic boolean isOutdated() {\n\t\treturn snapshot.isModified(getFile());\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * @since 4.10\n\t */\n\t@Override\n\tprotected byte[] readIncludedConfig(String relPath)\n\t\t\tthrows ConfigInvalidException {\n\t\tfinal File file;\n\t\tif (relPath.startsWith(\"~/\")) { //$NON-NLS-1$\n\t\t\tfile = fs.resolve(fs.userHome(), relPath.substring(2));\n\t\t} else {\n\t\t\tfile = fs.resolve(configFile.getParentFile(), relPath);\n\t\t}\n\n\t\tif (!file.exists()) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\treturn IO.readFully(file);\n\t\t} catch (FileNotFoundException e) {\n\t\t\treturn null;\n\t\t} catch (IOException ioe) {\n\t\t\tthrow new ConfigInvalidException(MessageFormat\n\t\t\t\t\t.format(JGitText.get().cannotReadFile, relPath), ioe);\n\t\t}\n\t}\n}" }, { "identifier": "ExecutionResult", "path": "org.eclipse.jgit/src/org/eclipse/jgit/util/FS.java", "snippet": "public static class ExecutionResult {\n\tprivate TemporaryBuffer stdout;\n\n\tprivate TemporaryBuffer stderr;\n\n\tprivate int rc;\n\n\t/**\n\t * @param stdout\n\t * stdout stream\n\t * @param stderr\n\t * stderr stream\n\t * @param rc\n\t * return code\n\t */\n\tpublic ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,\n\t\t\tint rc) {\n\t\tthis.stdout = stdout;\n\t\tthis.stderr = stderr;\n\t\tthis.rc = rc;\n\t}\n\n\t/**\n\t * Get buffered standard output stream\n\t *\n\t * @return buffered standard output stream\n\t */\n\tpublic TemporaryBuffer getStdout() {\n\t\treturn stdout;\n\t}\n\n\t/**\n\t * Get buffered standard error stream\n\t *\n\t * @return buffered standard error stream\n\t */\n\tpublic TemporaryBuffer getStderr() {\n\t\treturn stderr;\n\t}\n\n\t/**\n\t * Get the return code of the process\n\t *\n\t * @return the return code of the process\n\t */\n\tpublic int getRc() {\n\t\treturn rc;\n\t}\n}" } ]
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_CMD; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_GUITOOL; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_PATH; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_PROMPT; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_TOOL; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_TRUST_EXIT_CODE; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_MERGETOOL_SECTION; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_MERGE_SECTION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.eclipse.jgit.lib.internal.BooleanTriState; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS.ExecutionResult; import org.junit.Test;
4,434
ExternalMergeTool externalTool = tools.get(customToolName); manager.merge(local, remote, merged, base, null, externalTool); assertEchoCommandHasCorrectOutput(); } @Test public void testUserDefinedToolWithPrompt() throws Exception { String customToolName = "customTool"; String command = getEchoCommand(); FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, customToolName, CONFIG_KEY_CMD, command); MergeTools manager = new MergeTools(db); PromptHandler promptHandler = PromptHandler.acceptPrompt(); MissingToolHandler noToolHandler = new MissingToolHandler(); manager.merge(local, remote, merged, base, null, Optional.of(customToolName), BooleanTriState.TRUE, false, promptHandler, noToolHandler); assertEchoCommandHasCorrectOutput(); List<String> actualToolPrompts = promptHandler.toolPrompts; List<String> expectedToolPrompts = Arrays.asList("customTool"); assertEquals("Expected a user prompt for custom tool call", expectedToolPrompts, actualToolPrompts); assertEquals("Expected to no informing about missing tools", Collections.EMPTY_LIST, noToolHandler.missingTools); } @Test public void testUserDefinedToolWithCancelledPrompt() throws Exception { MergeTools manager = new MergeTools(db); PromptHandler promptHandler = PromptHandler.cancelPrompt(); MissingToolHandler noToolHandler = new MissingToolHandler(); Optional<ExecutionResult> result = manager.merge(local, remote, merged, base, null, Optional.empty(), BooleanTriState.TRUE, false, promptHandler, noToolHandler); assertFalse("Expected no result if user cancels the operation", result.isPresent()); } @Test public void testAllTools() { FileBasedConfig config = db.getConfig(); String customToolName = "customTool"; config.setString(CONFIG_MERGETOOL_SECTION, customToolName, CONFIG_KEY_CMD, "echo"); MergeTools manager = new MergeTools(db); Set<String> actualToolNames = manager.getAllToolNames(); Set<String> expectedToolNames = new LinkedHashSet<>(); expectedToolNames.add(customToolName); CommandLineMergeTool[] defaultTools = CommandLineMergeTool.values(); for (CommandLineMergeTool defaultTool : defaultTools) { String toolName = defaultTool.name(); expectedToolNames.add(toolName); } assertEquals("Incorrect set of external merge tools", expectedToolNames, actualToolNames); } @Test public void testOverridePredefinedToolPath() { String toolName = CommandLineMergeTool.guiffy.name(); String customToolPath = "/usr/bin/echo"; FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD, "echo"); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_PATH, customToolPath); MergeTools manager = new MergeTools(db); Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools(); ExternalMergeTool mergeTool = tools.get(toolName); assertNotNull("Expected tool \"" + toolName + "\" to be user defined", mergeTool); String toolPath = mergeTool.getPath(); assertEquals("Expected external merge tool to have an overriden path", customToolPath, toolPath); } @Test public void testUserDefinedTools() { FileBasedConfig config = db.getConfig(); String customToolname = "customTool"; config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_CMD, "echo"); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_PATH, "/usr/bin/echo"); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_PROMPT, String.valueOf(false)); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_GUITOOL, String.valueOf(false)); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(false)); MergeTools manager = new MergeTools(db); Set<String> actualToolNames = manager.getUserDefinedTools().keySet(); Set<String> expectedToolNames = new LinkedHashSet<>(); expectedToolNames.add(customToolname); assertEquals("Incorrect set of external merge tools", expectedToolNames, actualToolNames); } @Test public void testCompare() throws ToolException { String toolName = "customTool"; FileBasedConfig config = db.getConfig(); // the default merge tool is configured without a subsection String subsection = null;
/* * Copyright (C) 2020-2022, Simeon Andreev <[email protected]> and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.internal.diffmergetool; /** * Testing external merge tools. */ public class ExternalMergeToolTest extends ExternalToolTestCase { @Test(expected = ToolException.class) public void testUserToolWithError() throws Exception { String toolName = "customTool"; int errorReturnCode = 1; String command = "exit " + errorReturnCode; FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD, command); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(Boolean.TRUE)); invokeMerge(toolName); fail("Expected exception to be thrown due to external tool exiting with error code: " + errorReturnCode); } @Test(expected = ToolException.class) public void testUserToolWithCommandNotFoundError() throws Exception { String toolName = "customTool"; int errorReturnCode = 127; // command not found String command = "exit " + errorReturnCode; FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD, command); invokeMerge(toolName); fail("Expected exception to be thrown due to external tool exiting with error code: " + errorReturnCode); } @Test public void testKdiff3() throws Exception { assumePosixPlatform(); CommandLineMergeTool autoMergingTool = CommandLineMergeTool.kdiff3; assumeMergeToolIsAvailable(autoMergingTool); CommandLineMergeTool tool = autoMergingTool; PreDefinedMergeTool externalTool = new PreDefinedMergeTool(tool.name(), tool.getPath(), tool.getParameters(true), tool.getParameters(false), tool.isExitCodeTrustable() ? BooleanTriState.TRUE : BooleanTriState.FALSE); MergeTools manager = new MergeTools(db); ExecutionResult result = manager.merge(local, remote, merged, null, null, externalTool); assertEquals("Expected merge tool to succeed", 0, result.getRc()); List<String> actualLines = Files.readAllLines(mergedFile.toPath()); String actualMergeResult = String.join(System.lineSeparator(), actualLines); String expectedMergeResult = DEFAULT_CONTENT; assertEquals( "Failed to merge equal local and remote versions with pre-defined tool: " + tool.getPath(), expectedMergeResult, actualMergeResult); } @Test public void testUserDefinedTool() throws Exception { String customToolName = "customTool"; String command = getEchoCommand(); FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, customToolName, CONFIG_KEY_CMD, command); MergeTools manager = new MergeTools(db); Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools(); ExternalMergeTool externalTool = tools.get(customToolName); manager.merge(local, remote, merged, base, null, externalTool); assertEchoCommandHasCorrectOutput(); } @Test public void testUserDefinedToolWithPrompt() throws Exception { String customToolName = "customTool"; String command = getEchoCommand(); FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, customToolName, CONFIG_KEY_CMD, command); MergeTools manager = new MergeTools(db); PromptHandler promptHandler = PromptHandler.acceptPrompt(); MissingToolHandler noToolHandler = new MissingToolHandler(); manager.merge(local, remote, merged, base, null, Optional.of(customToolName), BooleanTriState.TRUE, false, promptHandler, noToolHandler); assertEchoCommandHasCorrectOutput(); List<String> actualToolPrompts = promptHandler.toolPrompts; List<String> expectedToolPrompts = Arrays.asList("customTool"); assertEquals("Expected a user prompt for custom tool call", expectedToolPrompts, actualToolPrompts); assertEquals("Expected to no informing about missing tools", Collections.EMPTY_LIST, noToolHandler.missingTools); } @Test public void testUserDefinedToolWithCancelledPrompt() throws Exception { MergeTools manager = new MergeTools(db); PromptHandler promptHandler = PromptHandler.cancelPrompt(); MissingToolHandler noToolHandler = new MissingToolHandler(); Optional<ExecutionResult> result = manager.merge(local, remote, merged, base, null, Optional.empty(), BooleanTriState.TRUE, false, promptHandler, noToolHandler); assertFalse("Expected no result if user cancels the operation", result.isPresent()); } @Test public void testAllTools() { FileBasedConfig config = db.getConfig(); String customToolName = "customTool"; config.setString(CONFIG_MERGETOOL_SECTION, customToolName, CONFIG_KEY_CMD, "echo"); MergeTools manager = new MergeTools(db); Set<String> actualToolNames = manager.getAllToolNames(); Set<String> expectedToolNames = new LinkedHashSet<>(); expectedToolNames.add(customToolName); CommandLineMergeTool[] defaultTools = CommandLineMergeTool.values(); for (CommandLineMergeTool defaultTool : defaultTools) { String toolName = defaultTool.name(); expectedToolNames.add(toolName); } assertEquals("Incorrect set of external merge tools", expectedToolNames, actualToolNames); } @Test public void testOverridePredefinedToolPath() { String toolName = CommandLineMergeTool.guiffy.name(); String customToolPath = "/usr/bin/echo"; FileBasedConfig config = db.getConfig(); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_CMD, "echo"); config.setString(CONFIG_MERGETOOL_SECTION, toolName, CONFIG_KEY_PATH, customToolPath); MergeTools manager = new MergeTools(db); Map<String, ExternalMergeTool> tools = manager.getUserDefinedTools(); ExternalMergeTool mergeTool = tools.get(toolName); assertNotNull("Expected tool \"" + toolName + "\" to be user defined", mergeTool); String toolPath = mergeTool.getPath(); assertEquals("Expected external merge tool to have an overriden path", customToolPath, toolPath); } @Test public void testUserDefinedTools() { FileBasedConfig config = db.getConfig(); String customToolname = "customTool"; config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_CMD, "echo"); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_PATH, "/usr/bin/echo"); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_PROMPT, String.valueOf(false)); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_GUITOOL, String.valueOf(false)); config.setString(CONFIG_MERGETOOL_SECTION, customToolname, CONFIG_KEY_TRUST_EXIT_CODE, String.valueOf(false)); MergeTools manager = new MergeTools(db); Set<String> actualToolNames = manager.getUserDefinedTools().keySet(); Set<String> expectedToolNames = new LinkedHashSet<>(); expectedToolNames.add(customToolname); assertEquals("Incorrect set of external merge tools", expectedToolNames, actualToolNames); } @Test public void testCompare() throws ToolException { String toolName = "customTool"; FileBasedConfig config = db.getConfig(); // the default merge tool is configured without a subsection String subsection = null;
config.setString(CONFIG_MERGE_SECTION, subsection, CONFIG_KEY_TOOL,
4
2023-10-20 15:09:17+00:00
8k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/entity/Lizard.java
[ { "identifier": "NaturalistEntityTypes", "path": "common/src/main/java/com/starfish_studios/naturalist/core/registry/NaturalistEntityTypes.java", "snippet": "public class NaturalistEntityTypes {\n\n // PROJECTILES\n\n\n public static final Supplier<EntityType<ThrownDuckEgg>> DUCK_EGG = CommonPlatformHelper.registerEntityType(\"duck_egg\", ThrownDuckEgg::new, MobCategory.MISC, 0.25F, 0.25F, 16);\n\n // MOBS\n\n public static final Supplier<EntityType<Snail>> SNAIL = CommonPlatformHelper.registerEntityType(\"snail\", Snail::new, MobCategory.CREATURE, 0.7F, 0.7F, 10);\n public static final Supplier<EntityType<Bear>> BEAR = CommonPlatformHelper.registerEntityType(\"bear\", Bear::new, MobCategory.CREATURE, 1.4F, 1.7F, 10);\n public static final Supplier<EntityType<Butterfly>> BUTTERFLY = CommonPlatformHelper.registerEntityType(\"butterfly\", Butterfly::new, MobCategory.CREATURE, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Moth>> MOTH = CommonPlatformHelper.registerEntityType(\"moth\", Moth::new, MobCategory.CREATURE, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Firefly>> FIREFLY = CommonPlatformHelper.registerEntityType(\"firefly\", Firefly::new, MobCategory.AMBIENT, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Snake>> SNAKE = CommonPlatformHelper.registerEntityType(\"snake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Snake>> CORAL_SNAKE = CommonPlatformHelper.registerEntityType(\"coral_snake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Snake>> RATTLESNAKE = CommonPlatformHelper.registerEntityType(\"rattlesnake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Deer>> DEER = CommonPlatformHelper.registerEntityType(\"deer\", Deer::new, MobCategory.CREATURE, 1.3F, 1.6F, 10);\n public static final Supplier<EntityType<Bird>> BLUEJAY = CommonPlatformHelper.registerEntityType(\"bluejay\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> CANARY = CommonPlatformHelper.registerEntityType(\"canary\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> CARDINAL = CommonPlatformHelper.registerEntityType(\"cardinal\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> ROBIN = CommonPlatformHelper.registerEntityType(\"robin\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Caterpillar>> CATERPILLAR = CommonPlatformHelper.registerEntityType(\"caterpillar\", Caterpillar::new, MobCategory.CREATURE, 0.4F, 0.4F, 10);\n public static final Supplier<EntityType<Rhino>> RHINO = CommonPlatformHelper.registerEntityType(\"rhino\", Rhino::new, MobCategory.CREATURE, 2.5F, 3.0F, 10);\n public static final Supplier<EntityType<Lion>> LION = CommonPlatformHelper.registerEntityType(\"lion\", Lion::new, MobCategory.CREATURE, 1.5F, 1.8F, 10);\n public static final Supplier<EntityType<Elephant>> ELEPHANT = CommonPlatformHelper.registerEntityType(\"elephant\", Elephant::new, MobCategory.CREATURE, 2.5F, 3.5F, 10);\n public static final Supplier<EntityType<Zebra>> ZEBRA = CommonPlatformHelper.registerEntityType(\"zebra\", Zebra::new, MobCategory.CREATURE, 1.3964844f, 1.6f, 10);\n public static final Supplier<EntityType<Giraffe>> GIRAFFE = CommonPlatformHelper.registerEntityType(\"giraffe\", Giraffe::new, MobCategory.CREATURE, 1.9f, 5.4f, 10);\n public static final Supplier<EntityType<Hippo>> HIPPO = CommonPlatformHelper.registerEntityType(\"hippo\", Hippo::new, MobCategory.CREATURE, 1.8F, 1.8F, 10);\n public static final Supplier<EntityType<Vulture>> VULTURE = CommonPlatformHelper.registerEntityType(\"vulture\", Vulture::new, MobCategory.CREATURE, 0.9f, 0.5f, 10);\n public static final Supplier<EntityType<Boar>> BOAR = CommonPlatformHelper.registerEntityType(\"boar\", Boar::new, MobCategory.CREATURE, 0.9f, 0.9f, 10);\n\n public static final Supplier<EntityType<Dragonfly>> DRAGONFLY = CommonPlatformHelper.registerEntityType(\"dragonfly\", Dragonfly::new, MobCategory.AMBIENT, 0.9F, 0.7F, 8);\n public static final Supplier<EntityType<Catfish>> CATFISH = CommonPlatformHelper.registerEntityType(\"catfish\", Catfish::new, MobCategory.WATER_AMBIENT, 1.0F, 0.7F, 8);\n public static final Supplier<EntityType<Alligator>> ALLIGATOR = CommonPlatformHelper.registerEntityType(\"alligator\", Alligator::new, MobCategory.CREATURE, 1.8F, 0.8F, 10);\n public static final Supplier<EntityType<Bass>> BASS = CommonPlatformHelper.registerEntityType(\"bass\", Bass::new, MobCategory.WATER_AMBIENT, 0.7f, 0.4f, 4);\n public static final Supplier<EntityType<Lizard>> LIZARD = CommonPlatformHelper.registerEntityType(\"lizard\", Lizard::new, MobCategory.CREATURE, 0.8F, 0.5F, 10);\n public static final Supplier<EntityType<LizardTail>> LIZARD_TAIL = CommonPlatformHelper.registerEntityType(\"lizard_tail\", LizardTail::new, MobCategory.CREATURE, 0.7f, 0.5f, 10);\n public static final Supplier<EntityType<Tortoise>> TORTOISE = CommonPlatformHelper.registerEntityType(\"tortoise\", Tortoise::new, MobCategory.CREATURE, 1.2F, 0.875F, 10);\n public static final Supplier<EntityType<Duck>> DUCK = CommonPlatformHelper.registerEntityType(\"duck\", Duck::new, MobCategory.CREATURE, 0.6F, 1.0F, 10);\n public static final Supplier<EntityType<Hyena>> HYENA = CommonPlatformHelper.registerEntityType(\"hyena\", Hyena::new, MobCategory.CREATURE, 1.1F, 1.3F, 10);\n public static final Supplier<EntityType<Ostrich>> OSTRICH = CommonPlatformHelper.registerEntityType(\"ostrich\", Ostrich::new, MobCategory.CREATURE, 1.0F, 2.0F, 10);\n public static final Supplier<EntityType<Termite>> TERMITE = CommonPlatformHelper.registerEntityType(\"termite\", Termite::new, MobCategory.CREATURE, 1.0F, 0.7F, 10);\n\n\n public static void init() {}\n}" }, { "identifier": "NaturalistTags", "path": "common/src/main/java/com/starfish_studios/naturalist/core/registry/NaturalistTags.java", "snippet": "public class NaturalistTags {\n public static class BlockTags {\n\n public static final TagKey<Block> MOTHS_ATTRACTED_TO = tag(\"moths_attracted_to\");\n\n public static final TagKey<Block> FIREFLIES_SPAWNABLE_ON = tag(\"fireflies_spawnable_on\");\n public static final TagKey<Block> DRAGONFLIES_SPAWNABLE_ON = tag(\"dragonflies_spawnable_on\");\n public static final TagKey<Block> VULTURES_SPAWNABLE_ON = tag(\"vultures_spawnable_on\");\n public static final TagKey<Block> DUCKS_SPAWNABLE_ON = tag(\"ducks_spawnable_on\");\n\n\n public static final TagKey<Block> RHINO_CHARGE_BREAKABLE = tag(\"rhino_charge_breakable\");\n public static final TagKey<Block> VULTURE_PERCH_BLOCKS = tag(\"vulture_perch_blocks\");\n\n\n public static final TagKey<Block> CATTAIL_PLACEABLE = tag(\"cattail_placeable\");\n public static final TagKey<Block> ALLIGATOR_EGG_LAYABLE_ON = tag(\"alligator_egg_layable_on\");\n public static final TagKey<Block> TORTOISE_EGG_LAYABLE_ON = tag(\"tortoise_egg_layable_on\");\n\n\n private static TagKey<Block> tag(String name) {\n return TagKey.create(Registry.BLOCK_REGISTRY, new ResourceLocation(Naturalist.MOD_ID, name));\n }\n }\n\n public static class ItemTags {\n\n public static final TagKey<Item> HYENA_FOOD_ITEMS = tag(\"hyena_food_items\");\n public static final TagKey<Item> OSTRICH_FOOD_ITEMS = tag(\"ostrich_food_items\");\n\n public static final TagKey<Item> BEAR_TEMPT_ITEMS = tag(\"bear_tempt_items\");\n public static final TagKey<Item> SNAKE_TEMPT_ITEMS = tag(\"snake_tempt_items\");\n public static final TagKey<Item> SNAKE_TAME_ITEMS = tag(\"snake_tame_items\");\n public static final TagKey<Item> BIRD_FOOD_ITEMS = tag(\"bird_food_items\");\n public static final TagKey<Item> GIRAFFE_FOOD_ITEMS = tag(\"giraffe_food_items\");\n public static final TagKey<Item> BOAR_FOOD_ITEMS = tag(\"boar_food_items\");\n public static final TagKey<Item> ALLIGATOR_FOOD_ITEMS = tag(\"alligator_food_items\");\n public static final TagKey<Item> LIZARD_TEMPT_ITEMS = tag(\"lizard_tempt_items\");\n public static final TagKey<Item> TORTOISE_TEMPT_ITEMS = tag(\"tortoise_tempt_items\");\n public static final TagKey<Item> DUCK_FOOD_ITEMS = tag(\"duck_food_items\");\n\n private static TagKey<Item> tag(String name) {\n return TagKey.create(Registry.ITEM_REGISTRY, new ResourceLocation(Naturalist.MOD_ID, name));\n }\n }\n\n public static class EntityTypes {\n public static final TagKey<EntityType<?>> OSTRICH_PREDATORS = tag(\"ostrich_predators\");\n public static final TagKey<EntityType<?>> BEAR_HOSTILES = tag(\"bear_hostiles\");\n public static final TagKey<EntityType<?>> SNAKE_HOSTILES = tag(\"snake_hostiles\");\n public static final TagKey<EntityType<?>> DEER_PREDATORS = tag(\"deer_predators\");\n public static final TagKey<EntityType<?>> LION_HOSTILES = tag(\"lion_hostiles\");\n public static final TagKey<EntityType<?>> VULTURE_HOSTILES = tag(\"vulture_hostiles\");\n public static final TagKey<EntityType<?>> CATFISH_HOSTILES = tag(\"catfish_hostiles\");\n public static final TagKey<EntityType<?>> ALLIGATOR_HOSTILES = tag(\"alligator_hostiles\");\n public static final TagKey<EntityType<?>> BOAR_HOSTILES = tag(\"boar_hostiles\");\n public static final TagKey<EntityType<?>> ANIMAL_CRATE_BLACKLISTED = tag(\"animal_crate_blacklist\");\n\n private static TagKey<EntityType<?>> tag(String name) {\n return TagKey.create(Registry.ENTITY_TYPE_REGISTRY, new ResourceLocation(Naturalist.MOD_ID, name));\n }\n }\n\n public static class Biomes {\n public static final TagKey<Biome> HAS_BEAR = tag(\"has_bear\");\n public static final TagKey<Biome> HAS_DEER = tag(\"has_deer\");\n public static final TagKey<Biome> HAS_SNAIL = tag(\"has_snail\");\n public static final TagKey<Biome> HAS_FIREFLY = tag(\"has_firefly\");\n public static final TagKey<Biome> HAS_BUTTERFLY = tag(\"has_butterfly\");\n public static final TagKey<Biome> HAS_SNAKE = tag(\"has_snake\");\n public static final TagKey<Biome> HAS_RATTLESNAKE = tag(\"has_rattlesnake\");\n public static final TagKey<Biome> HAS_CORAL_SNAKE = tag(\"has_coral_snake\");\n public static final TagKey<Biome> HAS_BLUEJAY = tag(\"has_bluejay\");\n public static final TagKey<Biome> HAS_CANARY = tag(\"has_canary\");\n public static final TagKey<Biome> HAS_CARDINAL = tag(\"has_cardinal\");\n public static final TagKey<Biome> HAS_ROBIN = tag(\"has_robin\");\n public static final TagKey<Biome> HAS_RHINO = tag(\"has_rhino\");\n public static final TagKey<Biome> HAS_LION = tag(\"has_lion\");\n public static final TagKey<Biome> HAS_ELEPHANT = tag(\"has_elephant\");\n public static final TagKey<Biome> HAS_ZEBRA = tag(\"has_zebra\");\n public static final TagKey<Biome> HAS_GIRAFFE = tag(\"has_giraffe\");\n public static final TagKey<Biome> HAS_HIPPO = tag(\"has_hippo\");\n public static final TagKey<Biome> HAS_VULTURE = tag(\"has_vulture\");\n public static final TagKey<Biome> HAS_BOAR = tag(\"has_boar\");\n public static final TagKey<Biome> HAS_DRAGONFLY = tag(\"has_dragonfly\");\n public static final TagKey<Biome> HAS_CATFISH = tag(\"has_catfish\");\n public static final TagKey<Biome> HAS_ALLIGATOR = tag(\"has_alligator\");\n public static final TagKey<Biome> HAS_BASS = tag(\"has_bass\");\n public static final TagKey<Biome> HAS_LIZARD = tag(\"has_lizard\");\n public static final TagKey<Biome> HAS_TORTOISE = tag(\"has_tortoise\");\n public static final TagKey<Biome> HAS_DUCK = tag(\"has_duck\");\n\n private static TagKey<Biome> tag(String name) {\n return TagKey.create(Registry.BIOME_REGISTRY, new ResourceLocation(Naturalist.MOD_ID, name));\n }\n }\n}" } ]
import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistTags; import net.minecraft.core.Holder; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.tags.BiomeTags; import net.minecraft.util.Mth; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; import org.jetbrains.annotations.Nullable; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import software.bernie.geckolib3.util.GeckoLibUtil;
3,916
package com.starfish_studios.naturalist.common.entity; public class Lizard extends TamableAnimal implements IAnimatable { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> HAS_TAIL = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.BOOLEAN);
package com.starfish_studios.naturalist.common.entity; public class Lizard extends TamableAnimal implements IAnimatable { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> HAS_TAIL = SynchedEntityData.defineId(Lizard.class, EntityDataSerializers.BOOLEAN);
private static final Ingredient TEMPT_INGREDIENT = Ingredient.of(NaturalistTags.ItemTags.LIZARD_TEMPT_ITEMS);
1
2023-10-16 21:54:32+00:00
8k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java
[ { "identifier": "BackupEntry", "path": "app/src/main/java/cn/wq/myandroidtoolspro/model/BackupEntry.java", "snippet": "public class BackupEntry extends ComponentEntry {\n public String appName;\n /**\n * @see cn.wq.myandroidtoolspro.helper.IfwUtil#COMPONENT_FLAG_ACTIVITY\n */\n public int cType;\n\n public boolean isSystem;\n}" }, { "identifier": "ComponentEntry", "path": "app/src/main/java/cn/wq/myandroidtoolspro/model/ComponentEntry.java", "snippet": "public class ComponentEntry extends ComponentModel {\r\n\tpublic boolean enabled;\r\n}\r" }, { "identifier": "AbstractComponentAdapter", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/adapter/AbstractComponentAdapter.java", "snippet": "public abstract class AbstractComponentAdapter<T extends ComponentEntry>\r\n extends RecyclerView.Adapter\r\n implements Filterable{\r\n private List<T> list;\r\n private boolean isFullName;\r\n private ComponentFilter mFilter;\r\n private List<T> originalData;\r\n private final Object mLock = new Object();\r\n protected Context mContext;\r\n protected int primaryTextColor;\r\n protected int redTextColor;\r\n\r\n// public AbstractComponentAdapter() {\r\n// super();\r\n// this.list = new ArrayList<>();\r\n// }\r\n\r\n public AbstractComponentAdapter(Context context) {\r\n this.list = new ArrayList<>();\r\n mContext = context;\r\n primaryTextColor = Utils.getColorFromAttr(context, android.R.attr.textColorPrimary);\r\n redTextColor = ContextCompat.getColor(mContext, R.color.holo_red_light);\r\n }\r\n\r\n public T getItem(int position) {\r\n return list.get(position);\r\n }\r\n\r\n public void setData(List<T> list) {\r\n this.list.clear();\r\n if (list != null) {\r\n this.list.addAll(list);\r\n }\r\n\r\n //wq:搜索后禁用 刷新状态\r\n if(originalData!=null){\r\n originalData.clear();\r\n originalData=null;\r\n }\r\n\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return list.size();\r\n }\r\n\r\n public boolean toggleName() {\r\n isFullName = !isFullName;\r\n notifyDataSetChanged();\r\n return isFullName;\r\n }\r\n\r\n public boolean getIsFullName() {\r\n return isFullName;\r\n }\r\n\r\n @Override\r\n public Filter getFilter() {\r\n if (mFilter == null) {\r\n mFilter = new ComponentFilter();\r\n }\r\n return mFilter;\r\n }\r\n\r\n private class ComponentFilter extends Filter {\r\n @Override\r\n protected void publishResults(CharSequence constraint,\r\n FilterResults results) {\r\n list = (List<T>) results.values;\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n protected FilterResults performFiltering(CharSequence constraint) {\r\n final FilterResults results = new FilterResults();\r\n if (originalData == null) {\r\n synchronized (mLock) {\r\n originalData = new ArrayList<>(list);\r\n }\r\n }\r\n\r\n List<T> tempList;\r\n if (TextUtils.isEmpty(constraint)||constraint.toString().trim().length()==0) {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n results.values = tempList;\r\n results.count = tempList.size();\r\n } else {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n\r\n final List<T> newValues = new ArrayList<>();\r\n int type=-1;\r\n for (T entry : tempList) {\r\n if(type<0){\r\n type=0;\r\n if(entry instanceof ReceiverWithActionEntry){\r\n type=1;\r\n }\r\n }\r\n\r\n //最好trim一下\r\n String query=constraint.toString().trim().toLowerCase(Locale.getDefault());\r\n String lowerName=entry.className.toLowerCase(Locale.getDefault());\r\n if ((isFullName && lowerName.contains (query)\r\n || (!isFullName && lowerName.substring(lowerName.lastIndexOf(\".\")+1).contains(query)))){\r\n newValues.add(entry);\r\n }else if(type>0){\r\n ReceiverWithActionEntry receiverEntry= (ReceiverWithActionEntry) entry;\r\n if(receiverEntry.appName.toLowerCase(Locale.getDefault()).contains(query)){\r\n newValues.add(entry);\r\n }\r\n }\r\n }\r\n\r\n results.values = newValues;\r\n results.count = newValues.size();\r\n }\r\n\r\n return results;\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "AppInfoForManageFragment2", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/AppInfoForManageFragment2.java", "snippet": "public class AppInfoForManageFragment2 extends BaseFragment {\r\n private static final String TAG = \"AppInfoForManageFrag\";\r\n private ViewPager mViewPager;\r\n private TabLayout mTabLayout;\r\n private String packageName;\r\n private CustomProgressDialogFragment dialog;\r\n private Context mContext;\r\n private CompositeDisposable compositeDisposable = new CompositeDisposable();\r\n public static IfwUtil.IfwEntry mIfwEntry;\r\n\r\n @Override\r\n public void onAttach(Context context) {\r\n super.onAttach(context);\r\n mContext = context;\r\n }\r\n\r\n public static AppInfoForManageFragment2 newInstance(Bundle args){\r\n AppInfoForManageFragment2 f=new AppInfoForManageFragment2();\r\n\t\tf.setArguments(args);\r\n\t\treturn f;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void onActivityCreated(Bundle savedInstanceState) {\r\n\t\tsuper.onActivityCreated(savedInstanceState);\r\n\t\tBundle data=getArguments();\r\n// packageName = data.getString(\"packageName\");\r\n\r\n initActionbar(2,data.getString(\"title\"));\r\n setToolbarLogo(packageName);\r\n\t}\r\n\r\n @Override\r\n public void onDestroy() {\r\n super.onDestroy();\r\n if (compositeDisposable != null) {\r\n compositeDisposable.clear();\r\n }\r\n if (mIfwEntry != null) {\r\n mIfwEntry.clear();\r\n }\r\n }\r\n\r\n @Override\r\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n\t\t\tBundle savedInstanceState) {\r\n setHasOptionsMenu(true);\r\n\r\n Bundle data=getArguments();\r\n if (data != null) {\r\n packageName = data.getString(\"packageName\");\r\n }\r\n\r\n final View root = inflater.inflate(R.layout.fragment_component_parent, container, false);\r\n if (!Utils.isPmByIfw(mContext)) {\r\n initViews(root);\r\n } else {\r\n Disposable disposable = Observable.create(new ObservableOnSubscribe<IfwUtil.IfwEntry>() {\r\n @Override\r\n public void subscribe(ObservableEmitter<IfwUtil.IfwEntry> emitter) throws Exception {\r\n IfwUtil.IfwEntry ifwEntry = IfwUtil.loadIfwFileForPkg(mContext, packageName, IfwUtil.COMPONENT_FLAG_ALL, false);\r\n emitter.onNext(ifwEntry);\r\n emitter.onComplete();\r\n }\r\n })\r\n .subscribeOn(Schedulers.io())\r\n .observeOn(AndroidSchedulers.mainThread())\r\n .doOnSubscribe(new Consumer<Disposable>() {\r\n @Override\r\n public void accept(Disposable disposable) {\r\n // TODO:wq 2019/4/17 最好是在布局中增加progressbar\r\n CustomProgressDialogFragment.showProgressDialog(\"loadIfw\", getFragmentManager());\r\n }\r\n })\r\n .doFinally(new Action() {\r\n @Override\r\n public void run() throws Exception {\r\n CustomProgressDialogFragment.hideProgressDialog(\"loadIfw\", getFragmentManager());\r\n }\r\n })\r\n .subscribe(new Consumer<IfwUtil.IfwEntry>() {\r\n @Override\r\n public void accept(IfwUtil.IfwEntry ifwEntry) throws Exception {\r\n mIfwEntry = ifwEntry;\r\n if (mIfwEntry == null) {\r\n Toast.makeText(mContext, R.string.load_ifw_by_root_failed, Toast.LENGTH_SHORT).show();\r\n return;\r\n } else if (mIfwEntry == IfwUtil.IfwEntry.ROOT_ERROR) {\r\n Toast.makeText(mContext, R.string.failed_to_gain_root, Toast.LENGTH_SHORT).show();\r\n return;\r\n }\r\n initViews(root);\r\n }\r\n }, new Consumer<Throwable>() {\r\n @Override\r\n public void accept(Throwable throwable) {\r\n throwable.printStackTrace();\r\n Log.e(TAG, \"loadIfwFileForPkg error\", throwable);\r\n Toast.makeText(mContext, R.string.load_ifw_by_root_failed, Toast.LENGTH_SHORT).show();\r\n }\r\n });\r\n\r\n compositeDisposable.add(disposable);\r\n }\r\n\t\treturn root;\r\n\t}\r\n\r\n private void initViews(View root) {\r\n mViewPager = (ViewPager) root.findViewById(R.id.view_pager);\r\n mViewPager.setAdapter(new MyPagerAdapter(this, getArguments()));\r\n mTabLayout = (TabLayout) root.findViewById(R.id.tab_layout);\r\n mTabLayout.setupWithViewPager(mViewPager);\r\n\r\n mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {\r\n private int pre_pos;\r\n\r\n @Override\r\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\r\n }\r\n\r\n @Override\r\n public void onPageSelected(int position) {\r\n if(pre_pos==position){\r\n return;\r\n }\r\n MultiSelectionRecyclerListFragment fragment=getFragment(pre_pos);\r\n if(fragment!=null){\r\n fragment.closeActionMode();\r\n }\r\n pre_pos = position;\r\n }\r\n\r\n @Override\r\n public void onPageScrollStateChanged(int state) {\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\r\n super.onCreateOptionsMenu(menu, inflater);\r\n\r\n if (!BuildConfig.isFree) {\r\n MenuItem manifest=menu.add(0, R.id.view_manifest, 0, R.string.view_manifest);\r\n MenuItemCompat.setShowAsAction(manifest,MenuItemCompat.SHOW_AS_ACTION_NEVER);\r\n\r\n MenuItem backup = menu.add(0, R.id.backup, 1, R.string.backup_disabled_of_an_app);\r\n MenuItemCompat.setShowAsAction(backup,MenuItemCompat.SHOW_AS_ACTION_NEVER);\r\n }\r\n\r\n }\r\n\r\n @Override\r\n public boolean onOptionsItemSelected(MenuItem item) {\r\n switch (item.getItemId()) {\r\n case R.id.view_manifest:\r\n Intent intent = new Intent(getContext(), ViewManifestActivity2.class);\r\n// Bundle args=getArguments();\r\n intent.putExtra(\"packageName\", packageName);\r\n// intent.putExtra(\"title\",args.getString(\"title\"));\r\n startActivity(intent);\r\n return true;\r\n case R.id.backup:\r\n backup();\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n private void backup() {\r\n setProgressDialogVisibility(true);\r\n\r\n StringBuilder sb = new StringBuilder();\r\n PackageManager pm = mContext.getPackageManager();\r\n\r\n List<ComponentModel> services= Utils.getComponentModels(mContext,packageName,4);\r\n for (ComponentModel s : services) {\r\n if (!Utils.isComponentEnabled(s, pm)) {\r\n sb.append(s.packageName)\r\n .append(\"/\")\r\n .append(s.className)\r\n .append(\"\\n\");\r\n }\r\n }\r\n\r\n String dirString= Environment.getExternalStorageDirectory() + \"/MyAndroidTools/\";\r\n File dir = new File(dirString);\r\n if (!dir.exists()) {\r\n dir.mkdirs();\r\n }\r\n\r\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyyMMdd_HHmm_SSS\", Locale.getDefault());\r\n String string= dirString+\"backup_\" + dateFormat.format(new Date());\r\n try {\r\n FileWriter writer = new FileWriter(new File(string));\r\n writer.write(sb.toString());\r\n writer.flush();\r\n writer.close();\r\n// Toast.makeText(mActivity, getString(R.string.backup_done, string), Toast.LENGTH_LONG).show();\r\n\r\n setProgressDialogVisibility(false);\r\n\r\n Bundle args = new Bundle();\r\n args.putString(\"path\",string);\r\n RenameDialogFragment renameDialog = new RenameDialogFragment();\r\n renameDialog.setArguments(args);\r\n renameDialog.show(getActivity().getSupportFragmentManager(),\"rename\");\r\n\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n setProgressDialogVisibility(false);\r\n Toast.makeText(mContext, R.string.operation_failed, Toast.LENGTH_SHORT).show();\r\n }\r\n\r\n }\r\n\r\n private void setProgressDialogVisibility(boolean visible) {\r\n if (visible) {\r\n if (dialog == null) {\r\n dialog = new CustomProgressDialogFragment();\r\n dialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);\r\n dialog.setCancelable(false);\r\n }\r\n\r\n if (!dialog.isVisible() && getActivity() != null && !getActivity().isFinishing()) {\r\n try {\r\n dialog.show(getActivity().getSupportFragmentManager(), \"dialog\");\r\n } catch (Exception e) {\r\n }\r\n }\r\n } else {\r\n if (dialog != null && getFragmentManager()!=null) {\r\n dialog.dismissAllowingStateLoss();\r\n }\r\n }\r\n }\r\n\r\n private MultiSelectionRecyclerListFragment getFragment(int position){\r\n return (MultiSelectionRecyclerListFragment) getChildFragmentManager().findFragmentByTag(\"android:switcher:\" + mViewPager.getId() + \":\"\r\n + position);\r\n }\r\n\t\r\n\tprivate class MyPagerAdapter extends FragmentPagerAdapter {\r\n\t\tprivate String[] titles;\r\n\t\tprivate Bundle args;\r\n private int actionModeBackground = -1;\r\n private int defaultTabBackground = -1;\r\n\t\t\r\n MyPagerAdapter(Fragment fragment,Bundle bundle) {\r\n\t\t\tsuper(fragment.getChildFragmentManager());\r\n\t\t\targs=bundle;\r\n titles=new String[]{fragment.getString(R.string.service),\r\n fragment.getString(R.string.broadcast_receiver),\r\n fragment.getString(R.string.activity),\r\n fragment.getString(R.string.content_provider)};\r\n\r\n actionModeBackground = Utils.getColorFromAttr(mContext,R.attr.actionModeBackground);\r\n defaultTabBackground = Utils.getColorFromAttr(mContext, R.attr.colorPrimary);\r\n }\r\n\r\n\t\t@Override\r\n\t\tpublic Fragment getItem(int position) {\r\n args.putBoolean(\"ignoreToolbar\",true);\r\n args.putBoolean(\"useParentIfw\", true);\r\n\r\n MultiSelectionRecyclerListFragment f;\r\n\t\t\tswitch (position) {\r\n\t\t\tcase 0:\r\n\t\t\t\tf = ServiceRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tcase 1:\r\n f = ReceiverRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tcase 2:\r\n f = ActivityRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tdefault:\r\n f = ProviderRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\t}\r\n f.addActionModeLefecycleCallback(mActionModeLefecycleCallback);\r\n return f;\r\n\t\t}\r\n\r\n private MultiSelectionRecyclerListFragment.ActionModeLefecycleCallback mActionModeLefecycleCallback\r\n =new MultiSelectionRecyclerListFragment.ActionModeLefecycleCallback() {\r\n @Override\r\n public void onModeCreated() {\r\n// mTabLayout.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.blue_grey_500));\r\n mTabLayout.setBackgroundColor(actionModeBackground);\r\n }\r\n\r\n /**\r\n * onDestroyActionMode 将 statusbar 颜色置为透明了,在 AppInfoActivity 中会显示成灰白\r\n * @see cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils.Controller#onDestroyActionMode(ActionMode)\r\n */\r\n @Override\r\n public void onModeDestroyed() {\r\n// mTabLayout.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.actionbar_color));\r\n mTabLayout.setBackgroundColor(defaultTabBackground);\r\n\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP\r\n && getActivity() != null\r\n && getActivity() instanceof AppInfoActivity) {\r\n getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getContext(),R.color.actionbar_color_dark));\r\n }\r\n }\r\n };\r\n\r\n\t\t@Override\r\n\t\tpublic int getCount() {\r\n\t\t\treturn titles.length;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic CharSequence getPageTitle(int position) {\r\n\t\t\treturn titles[position];\r\n\t\t}\r\n\t}\r\n\t\r\n}\r" } ]
import android.content.ComponentName; import android.content.Context; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.util.Xml; import com.tencent.mars.xlog.Log; import org.xmlpull.v1.XmlPullParser; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cn.wq.myandroidtoolspro.model.BackupEntry; import cn.wq.myandroidtoolspro.model.ComponentEntry; import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter; import cn.wq.myandroidtoolspro.recyclerview.fragment.AppInfoForManageFragment2;
4,091
package cn.wq.myandroidtoolspro.helper; public class IfwUtil { private static final String TAG = "IfwUtil"; private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled"; public static final int COMPONENT_FLAG_EMPTY = 0x00; public static final int COMPONENT_FLAG_ACTIVITY = 0x01; public static final int COMPONENT_FLAG_RECEIVER = 0x10; public static final int COMPONENT_FLAG_SERVICE = 0x100; public static final int COMPONENT_FLAG_ALL = 0x111; public static final String BACKUP_LOCAL_FILE_EXT = ".ifw"; public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀 public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀 /** * 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br> * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容 * * @param positions 某一类component的位置 */ public static boolean saveComponentIfw(Context context, @NonNull String packageName, IfwEntry ifwEntry,
package cn.wq.myandroidtoolspro.helper; public class IfwUtil { private static final String TAG = "IfwUtil"; private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled"; public static final int COMPONENT_FLAG_EMPTY = 0x00; public static final int COMPONENT_FLAG_ACTIVITY = 0x01; public static final int COMPONENT_FLAG_RECEIVER = 0x10; public static final int COMPONENT_FLAG_SERVICE = 0x100; public static final int COMPONENT_FLAG_ALL = 0x111; public static final String BACKUP_LOCAL_FILE_EXT = ".ifw"; public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀 public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀 /** * 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br> * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容 * * @param positions 某一类component的位置 */ public static boolean saveComponentIfw(Context context, @NonNull String packageName, IfwEntry ifwEntry,
@NonNull AbstractComponentAdapter<? extends ComponentEntry> adapter,
2
2023-10-18 14:32:49+00:00
8k
instana/otel-dc
host/src/main/java/com/instana/dc/host/impl/SimpHostDc.java
[ { "identifier": "AbstractHostDc", "path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java", "snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final String otelBackendUrl;\n private final boolean otelUsingHttp;\n private final int pollInterval;\n private final int callbackInterval;\n private final String serviceName;\n public final static String INSTRUMENTATION_SCOPE_PREFIX = \"otelcol/hostmetricsreceiver/\";\n\n private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();\n\n public AbstractHostDc(Map<String, String> properties, String hostSystem) {\n super(new HostRawMetricRegistry().getMap());\n\n String pollInt = properties.get(POLLING_INTERVAL);\n pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt);\n String callbackInt = properties.get(CALLBACK_INTERVAL);\n callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt);\n otelBackendUrl = properties.get(OTEL_BACKEND_URL);\n otelUsingHttp = \"true\".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP));\n String svcName = properties.get(OTEL_SERVICE_NAME);\n serviceName = svcName == null ? hostSystem : svcName;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n @Override\n public void initDC() throws Exception {\n Resource resource = getResourceAttributes();\n SdkMeterProvider sdkMeterProvider = this.getDefaultSdkMeterProvider(resource, otelBackendUrl, callbackInterval, otelUsingHttp, 10);\n OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProvider).build();\n initMeters(openTelemetry);\n registerMetrics();\n }\n\n private void initMeter(OpenTelemetry openTelemetry, String name) {\n Meter meter1 = openTelemetry.meterBuilder(INSTRUMENTATION_SCOPE_PREFIX + name).setInstrumentationVersion(\"1.0.0\").build();\n getMeters().put(name, meter1);\n }\n\n /* The purpose to overwrite this method is to comply with the \"hostmetrics\" receiver of\n * OpenTelemetry Contrib Collector.\n **/\n @Override\n public void initMeters(OpenTelemetry openTelemetry) {\n initMeter(openTelemetry, HostDcUtil.MeterName.CPU);\n initMeter(openTelemetry, HostDcUtil.MeterName.MEMORY);\n initMeter(openTelemetry, HostDcUtil.MeterName.NETWORK);\n initMeter(openTelemetry, HostDcUtil.MeterName.LOAD);\n initMeter(openTelemetry, HostDcUtil.MeterName.DISK);\n initMeter(openTelemetry, HostDcUtil.MeterName.FILESYSTEM);\n initMeter(openTelemetry, HostDcUtil.MeterName.PROCESSES);\n initMeter(openTelemetry, HostDcUtil.MeterName.PAGING);\n }\n\n\n @Override\n public void start() {\n exec.scheduleWithFixedDelay(this::collectData, 1, pollInterval, TimeUnit.SECONDS);\n }\n}" }, { "identifier": "HostDcUtil", "path": "host/src/main/java/com/instana/dc/host/HostDcUtil.java", "snippet": "public class HostDcUtil {\n private static final Logger logger = Logger.getLogger(HostDcUtil.class.getName());\n\n public static class MeterName{\n public static final String CPU = \"cpu\";\n public static final String MEMORY = \"memory\";\n public static final String NETWORK = \"network\";\n public static final String LOAD = \"load\";\n public static final String DISK = \"disk\";\n public static final String FILESYSTEM = \"filesystem\";\n public static final String PROCESSES = \"processes\";\n public static final String PAGING = \"paging\";\n }\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String SYSTEM_CPU_TIME_NAME = \"system.cpu.time\";\n public static final String SYSTEM_CPU_TIME_DESC = \"Seconds each logical CPU spent on each mode\";\n public static final String SYSTEM_CPU_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_MEMORY_USAGE_NAME = \"system.memory.usage\";\n public static final String SYSTEM_MEMORY_USAGE_DESC = \"Bytes of memory in use\";\n public static final String SYSTEM_MEMORY_USAGE_UNIT = UNIT_BY;\n\n public static final String SYSTEM_CPU_LOAD1_NAME = \"system.cpu.load_average.1m\";\n public static final String SYSTEM_CPU_LOAD1_DESC = \"Average CPU Load over 1 minutes\";\n public static final String SYSTEM_CPU_LOAD1_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD5_NAME = \"system.cpu.load_average.5m\";\n public static final String SYSTEM_CPU_LOAD5_DESC = \"Average CPU Load over 5 minutes\";\n public static final String SYSTEM_CPU_LOAD5_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD15_NAME = \"system.cpu.load_average.15m\";\n public static final String SYSTEM_CPU_LOAD15_DESC = \"Average CPU Load over 15 minutes\";\n public static final String SYSTEM_CPU_LOAD15_UNIT = UNIT_1;\n\n public static final String SYSTEM_NETWORK_CONNECTIONS_NAME = \"system.network.connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_DESC = \"The number of connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_UNIT = \"{connections}\";\n\n public static final String SYSTEM_NETWORK_DROPPED_NAME = \"system.network.dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_DESC = \"The number of packets dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_UNIT = \"{packets}\";\n\n public static final String SYSTEM_NETWORK_ERRORS_NAME = \"system.network.errors\";\n public static final String SYSTEM_NETWORK_ERRORS_DESC = \"The number of errors encountered\";\n public static final String SYSTEM_NETWORK_ERRORS_UNIT = \"{errors}\";\n\n public static final String SYSTEM_NETWORK_IO_NAME = \"system.network.io\";\n public static final String SYSTEM_NETWORK_IO_DESC = \"The number of bytes transmitted and received\";\n public static final String SYSTEM_NETWORK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_NETWORK_PACKETS_NAME = \"system.network.packets\";\n public static final String SYSTEM_NETWORK_PACKETS_DESC = \"The number of packets transferred\";\n public static final String SYSTEM_NETWORK_PACKETS_UNIT = \"{packets}\";\n\n\n public static final String SYSTEM_DISK_IO_NAME = \"system.disk.io\";\n public static final String SYSTEM_DISK_IO_DESC = \"Disk bytes transferred\";\n public static final String SYSTEM_DISK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_DISK_IO_TIME_NAME = \"system.disk.io_time\";\n public static final String SYSTEM_DISK_IO_TIME_DESC = \"Time disk spent activated. On Windows, this is calculated as the inverse of disk idle time\";\n public static final String SYSTEM_DISK_IO_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_MERGED_NAME = \"system.disk.merged\";\n public static final String SYSTEM_DISK_MERGED_DESC = \"The number of disk reads/writes merged into single physical disk access operations\";\n public static final String SYSTEM_DISK_MERGED_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_OPERATION_TIME_NAME = \"system.disk.operation_time\";\n public static final String SYSTEM_DISK_OPERATION_TIME_DESC = \"Time spent in disk operations\";\n public static final String SYSTEM_DISK_OPERATION_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_OPERATIONS_NAME = \"system.disk.operations\";\n public static final String SYSTEM_DISK_OPERATIONS_DESC = \"Disk operations count\";\n public static final String SYSTEM_DISK_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_NAME = \"system.disk.pending_operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_DESC = \"The queue size of pending I/O operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_NAME = \"system.disk.weighted_io_time\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_DESC = \"Time disk spent activated multiplied by the queue length\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_UNIT = UNIT_S;\n\n\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_NAME = \"system.filesystem.inodes.usage\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_DESC = \"FileSystem inodes used\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_UNIT = \"{inodes}\";\n\n public static final String SYSTEM_FILESYSTEM_USAGE_NAME = \"system.filesystem.usage\";\n public static final String SYSTEM_FILESYSTEM_USAGE_DESC = \"Filesystem bytes used\";\n public static final String SYSTEM_FILESYSTEM_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PAGING_FAULTS_NAME = \"system.paging.faults\";\n public static final String SYSTEM_PAGING_FAULTS_DESC = \"The number of page faults\";\n public static final String SYSTEM_PAGING_FAULTS_UNIT = \"{faults}\";\n\n public static final String SYSTEM_PAGING_OPERATIONS_NAME = \"system.paging.operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_DESC = \"The number of paging operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_PAGING_USAGE_NAME = \"system.paging.usage\";\n public static final String SYSTEM_PAGING_USAGE_DESC = \"Swap (unix) or pagefile (windows) usage\";\n public static final String SYSTEM_PAGING_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PROCESSES_COUNT_NAME = \"system.processes.count\";\n public static final String SYSTEM_PROCESSES_COUNT_DESC = \"Total number of processes in each state\";\n public static final String SYSTEM_PROCESSES_COUNT_UNIT = \"{processes}\";\n\n public static final String SYSTEM_PROCESSES_CREATED_NAME = \"system.processes.created\";\n public static final String SYSTEM_PROCESSES_CREATED_DESC = \"Total number of created processes\";\n public static final String SYSTEM_PROCESSES_CREATED_UNIT = \"{processes}\";\n\n\n public static String readFileText(String filePath) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n int n = is.available();\n byte[] ba = new byte[n];\n is.read(ba);\n return new String(ba).trim();\n }\n }\n\n public static String readFileText(String filePath, int max) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n byte[] ba = new byte[max];\n int n = is.read(ba);\n return new String(ba, 0, n).trim();\n }\n }\n\n public static String readFileTextLine(String filePath) throws IOException {\n try (Reader rd = new FileReader(filePath)) {\n BufferedReader reader = new BufferedReader(rd);\n String line = reader.readLine();\n reader.close();\n return line;\n }\n }\n}" }, { "identifier": "mergeResourceAttributesFromEnv", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet": "public static Resource mergeResourceAttributesFromEnv(Resource resource) {\n String resAttrs = System.getenv(OTEL_RESOURCE_ATTRIBUTES);\n if (resAttrs != null) {\n for (String resAttr : resAttrs.split(\",\")) {\n String[] kv = resAttr.split(\"=\");\n if (kv.length != 2)\n continue;\n String key = kv[0].trim();\n String value = kv[1].trim();\n resource = resource.merge(Resource.create(Attributes.of(AttributeKey.stringKey(key), value)));\n }\n }\n return resource;\n}" }, { "identifier": "HostDcUtil", "path": "host/src/main/java/com/instana/dc/host/HostDcUtil.java", "snippet": "public class HostDcUtil {\n private static final Logger logger = Logger.getLogger(HostDcUtil.class.getName());\n\n public static class MeterName{\n public static final String CPU = \"cpu\";\n public static final String MEMORY = \"memory\";\n public static final String NETWORK = \"network\";\n public static final String LOAD = \"load\";\n public static final String DISK = \"disk\";\n public static final String FILESYSTEM = \"filesystem\";\n public static final String PROCESSES = \"processes\";\n public static final String PAGING = \"paging\";\n }\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String SYSTEM_CPU_TIME_NAME = \"system.cpu.time\";\n public static final String SYSTEM_CPU_TIME_DESC = \"Seconds each logical CPU spent on each mode\";\n public static final String SYSTEM_CPU_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_MEMORY_USAGE_NAME = \"system.memory.usage\";\n public static final String SYSTEM_MEMORY_USAGE_DESC = \"Bytes of memory in use\";\n public static final String SYSTEM_MEMORY_USAGE_UNIT = UNIT_BY;\n\n public static final String SYSTEM_CPU_LOAD1_NAME = \"system.cpu.load_average.1m\";\n public static final String SYSTEM_CPU_LOAD1_DESC = \"Average CPU Load over 1 minutes\";\n public static final String SYSTEM_CPU_LOAD1_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD5_NAME = \"system.cpu.load_average.5m\";\n public static final String SYSTEM_CPU_LOAD5_DESC = \"Average CPU Load over 5 minutes\";\n public static final String SYSTEM_CPU_LOAD5_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD15_NAME = \"system.cpu.load_average.15m\";\n public static final String SYSTEM_CPU_LOAD15_DESC = \"Average CPU Load over 15 minutes\";\n public static final String SYSTEM_CPU_LOAD15_UNIT = UNIT_1;\n\n public static final String SYSTEM_NETWORK_CONNECTIONS_NAME = \"system.network.connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_DESC = \"The number of connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_UNIT = \"{connections}\";\n\n public static final String SYSTEM_NETWORK_DROPPED_NAME = \"system.network.dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_DESC = \"The number of packets dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_UNIT = \"{packets}\";\n\n public static final String SYSTEM_NETWORK_ERRORS_NAME = \"system.network.errors\";\n public static final String SYSTEM_NETWORK_ERRORS_DESC = \"The number of errors encountered\";\n public static final String SYSTEM_NETWORK_ERRORS_UNIT = \"{errors}\";\n\n public static final String SYSTEM_NETWORK_IO_NAME = \"system.network.io\";\n public static final String SYSTEM_NETWORK_IO_DESC = \"The number of bytes transmitted and received\";\n public static final String SYSTEM_NETWORK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_NETWORK_PACKETS_NAME = \"system.network.packets\";\n public static final String SYSTEM_NETWORK_PACKETS_DESC = \"The number of packets transferred\";\n public static final String SYSTEM_NETWORK_PACKETS_UNIT = \"{packets}\";\n\n\n public static final String SYSTEM_DISK_IO_NAME = \"system.disk.io\";\n public static final String SYSTEM_DISK_IO_DESC = \"Disk bytes transferred\";\n public static final String SYSTEM_DISK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_DISK_IO_TIME_NAME = \"system.disk.io_time\";\n public static final String SYSTEM_DISK_IO_TIME_DESC = \"Time disk spent activated. On Windows, this is calculated as the inverse of disk idle time\";\n public static final String SYSTEM_DISK_IO_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_MERGED_NAME = \"system.disk.merged\";\n public static final String SYSTEM_DISK_MERGED_DESC = \"The number of disk reads/writes merged into single physical disk access operations\";\n public static final String SYSTEM_DISK_MERGED_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_OPERATION_TIME_NAME = \"system.disk.operation_time\";\n public static final String SYSTEM_DISK_OPERATION_TIME_DESC = \"Time spent in disk operations\";\n public static final String SYSTEM_DISK_OPERATION_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_OPERATIONS_NAME = \"system.disk.operations\";\n public static final String SYSTEM_DISK_OPERATIONS_DESC = \"Disk operations count\";\n public static final String SYSTEM_DISK_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_NAME = \"system.disk.pending_operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_DESC = \"The queue size of pending I/O operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_NAME = \"system.disk.weighted_io_time\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_DESC = \"Time disk spent activated multiplied by the queue length\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_UNIT = UNIT_S;\n\n\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_NAME = \"system.filesystem.inodes.usage\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_DESC = \"FileSystem inodes used\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_UNIT = \"{inodes}\";\n\n public static final String SYSTEM_FILESYSTEM_USAGE_NAME = \"system.filesystem.usage\";\n public static final String SYSTEM_FILESYSTEM_USAGE_DESC = \"Filesystem bytes used\";\n public static final String SYSTEM_FILESYSTEM_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PAGING_FAULTS_NAME = \"system.paging.faults\";\n public static final String SYSTEM_PAGING_FAULTS_DESC = \"The number of page faults\";\n public static final String SYSTEM_PAGING_FAULTS_UNIT = \"{faults}\";\n\n public static final String SYSTEM_PAGING_OPERATIONS_NAME = \"system.paging.operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_DESC = \"The number of paging operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_PAGING_USAGE_NAME = \"system.paging.usage\";\n public static final String SYSTEM_PAGING_USAGE_DESC = \"Swap (unix) or pagefile (windows) usage\";\n public static final String SYSTEM_PAGING_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PROCESSES_COUNT_NAME = \"system.processes.count\";\n public static final String SYSTEM_PROCESSES_COUNT_DESC = \"Total number of processes in each state\";\n public static final String SYSTEM_PROCESSES_COUNT_UNIT = \"{processes}\";\n\n public static final String SYSTEM_PROCESSES_CREATED_NAME = \"system.processes.created\";\n public static final String SYSTEM_PROCESSES_CREATED_DESC = \"Total number of created processes\";\n public static final String SYSTEM_PROCESSES_CREATED_UNIT = \"{processes}\";\n\n\n public static String readFileText(String filePath) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n int n = is.available();\n byte[] ba = new byte[n];\n is.read(ba);\n return new String(ba).trim();\n }\n }\n\n public static String readFileText(String filePath, int max) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n byte[] ba = new byte[max];\n int n = is.read(ba);\n return new String(ba, 0, n).trim();\n }\n }\n\n public static String readFileTextLine(String filePath) throws IOException {\n try (Reader rd = new FileReader(filePath)) {\n BufferedReader reader = new BufferedReader(rd);\n String line = reader.readLine();\n reader.close();\n return line;\n }\n }\n}" } ]
import com.instana.dc.host.AbstractHostDc; import com.instana.dc.host.HostDcUtil; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.ResourceAttributes; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.logging.Logger; import static com.instana.dc.DcUtil.mergeResourceAttributesFromEnv; import static com.instana.dc.host.HostDcUtil.*;
4,874
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostDc extends AbstractHostDc { private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName()); public SimpHostDc(Map<String, String> properties, String hostSystem) { super(properties, hostSystem); } public String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UnknownName"; } } public String getHostId() { try { return HostDcUtil.readFileText("/etc/machine-id"); } catch (IOException e) { return "UnknownID"; } } @Override public Resource getResourceAttributes() { String hostName = getHostName(); Resource resource = Resource.getDefault().merge( Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, getServiceName(), ResourceAttributes.SERVICE_INSTANCE_ID, hostName )) ); resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, hostName, ResourceAttributes.OS_TYPE, "linux", ResourceAttributes.HOST_ID, getHostId() )) );
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostDc extends AbstractHostDc { private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName()); public SimpHostDc(Map<String, String> properties, String hostSystem) { super(properties, hostSystem); } public String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UnknownName"; } } public String getHostId() { try { return HostDcUtil.readFileText("/etc/machine-id"); } catch (IOException e) { return "UnknownID"; } } @Override public Resource getResourceAttributes() { String hostName = getHostName(); Resource resource = Resource.getDefault().merge( Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, getServiceName(), ResourceAttributes.SERVICE_INSTANCE_ID, hostName )) ); resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, hostName, ResourceAttributes.OS_TYPE, "linux", ResourceAttributes.HOST_ID, getHostId() )) );
return mergeResourceAttributesFromEnv(resource);
2
2023-10-23 01:16:38+00:00
8k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/file/ios/BaseDarwinFileIO.java
[ { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}" }, { "identifier": "BaseFileIO", "path": "unidbg-api/src/main/java/com/github/unidbg/file/BaseFileIO.java", "snippet": "public abstract class BaseFileIO extends AbstractFileIO implements NewFileIO {\n\n public BaseFileIO(int oflags) {\n super(oflags);\n }\n\n}" }, { "identifier": "UnidbgFileFilter", "path": "unidbg-api/src/main/java/com/github/unidbg/file/UnidbgFileFilter.java", "snippet": "public class UnidbgFileFilter implements FileFilter {\n\n public static final String UNIDBG_PREFIX = \"__ignore.unidbg\";\n\n @Override\n public boolean accept(File pathname) {\n return !pathname.getName().startsWith(UNIDBG_PREFIX);\n }\n\n}" }, { "identifier": "DirectoryFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/DirectoryFileIO.java", "snippet": "public class DirectoryFileIO extends BaseDarwinFileIO {\n\n public static class DirectoryEntry {\n private final boolean isFile;\n private final String name;\n public DirectoryEntry(boolean isFile, String name) {\n this.isFile = isFile;\n this.name = name;\n }\n }\n\n private static DirectoryEntry[] createEntries(File dir) {\n List<DirectoryEntry> list = new ArrayList<>();\n File[] files = dir.listFiles(new UnidbgFileFilter());\n if (files != null) {\n Arrays.sort(files);\n for (File file : files) {\n list.add(new DirectoryEntry(file.isFile(), file.getName()));\n }\n }\n return list.toArray(new DirectoryEntry[0]);\n }\n\n private final String path;\n\n private final List<DirectoryEntry> entries;\n\n private final File dir;\n\n public DirectoryFileIO(int oflags, String path, File dir) {\n this(oflags, path, dir, createEntries(dir));\n }\n\n public DirectoryFileIO(int oflags, String path, DirectoryEntry... entries) {\n this(oflags, path, null, entries);\n }\n\n public DirectoryFileIO(int oflags, String path, File dir, DirectoryEntry... entries) {\n super(oflags);\n\n this.path = path;\n this.dir = dir;\n\n this.entries = new ArrayList<>();\n this.entries.add(new DirectoryEntry(false, \".\"));\n this.entries.add(new DirectoryEntry(false, \"..\"));\n if (entries != null) {\n Collections.addAll(this.entries, entries);\n }\n }\n\n @Override\n public int fstatfs(StatFS statFS) {\n return 0;\n }\n\n @Override\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n stat.st_dev = 1;\n stat.st_mode = IO.S_IFDIR | 0x777;\n stat.setSize(0);\n stat.st_blksize = 0;\n stat.st_ino = 7;\n stat.pack();\n return 0;\n }\n\n @Override\n public void close() {\n }\n\n @Override\n public String toString() {\n return path;\n }\n\n @Override\n public int fcntl(Emulator<?> emulator, int cmd, long arg) {\n if (cmd == F_GETPATH) {\n UnidbgPointer pointer = UnidbgPointer.pointer(emulator, arg);\n if (pointer != null) {\n pointer.setString(0, getPath());\n }\n return 0;\n }\n\n return super.fcntl(emulator, cmd, arg);\n }\n\n @Override\n public String getPath() {\n return path;\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n int offset = 0;\n for (Iterator<DirectoryFileIO.DirectoryEntry> iterator = this.entries.iterator(); iterator.hasNext(); ) {\n DirectoryFileIO.DirectoryEntry entry = iterator.next();\n byte[] data = entry.name.getBytes(StandardCharsets.UTF_8);\n long d_reclen = ARM.alignSize(data.length + 24, 8);\n\n if (offset + d_reclen >= bufSize) {\n break;\n }\n\n Dirent dirent = new Dirent(buf.share(offset));\n dirent.d_fileno = 1;\n dirent.d_reclen = (short) d_reclen;\n dirent.d_type = entry.isFile ? Dirent.DT_REG : Dirent.DT_DIR;\n dirent.d_namlen = (short) (data.length);\n dirent.d_name = Arrays.copyOf(data, data.length + 1);\n dirent.pack();\n offset += d_reclen;\n\n iterator.remove();\n }\n\n return offset;\n }\n\n @Override\n public int listxattr(Pointer namebuf, int size, int options) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", options=0x\" + Integer.toHexString(options));\n }\n return listxattr(dir, namebuf, size);\n }\n\n @Override\n public int removexattr(String name) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return removexattr(dir, name);\n }\n\n @Override\n public int setxattr(String name, byte[] data) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return setxattr(dir, name, data);\n }\n\n @Override\n public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return getxattr(emulator, dir, name, value, size);\n }\n\n @Override\n public int chmod(int mode) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", mode=0x\" + Integer.toHexString(mode));\n }\n return chmod(dir, mode);\n }\n\n @Override\n public int chown(int uid, int gid) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", uid=\" + uid + \", gid=\" + gid);\n }\n return chown(dir, uid, gid);\n }\n\n @Override\n public int chflags(int flags) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", flags=0x\" + Integer.toHexString(flags));\n }\n return chflags(dir, flags);\n }\n}" }, { "identifier": "AttrList", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrList.java", "snippet": "public class AttrList extends UnidbgStructure {\n\n public AttrList(Pointer p) {\n super(p);\n unpack();\n }\n\n public short bitmapcount; /* number of attr. bit sets in list (should be 5) */\n public short reserved; /* (to maintain 4-byte alignment) */\n\n public AttributeSet attributeSet;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"bitmapcount\", \"reserved\", \"attributeSet\");\n }\n\n}" }, { "identifier": "AttrReference", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrReference.java", "snippet": "public class AttrReference extends UnidbgStructure {\n\n private final byte[] bytes;\n\n public AttrReference(Pointer p, byte[] bytes) {\n super(p);\n this.bytes = bytes;\n attr_length = (int) ARM.alignSize(bytes.length + 1, 8);\n }\n\n public int attr_dataoffset;\n public int attr_length;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"attr_dataoffset\", \"attr_length\");\n }\n\n private boolean started;\n\n public void check(UnidbgStructure structure, int size) {\n if (structure == this) {\n started = true;\n }\n\n if (started) {\n attr_dataoffset += size;\n }\n }\n\n public void writeAttr(Pointer pointer) {\n pointer.write(0, Arrays.copyOf(bytes, attr_length), 0, attr_length);\n pack();\n }\n}" }, { "identifier": "AttributeSet", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttributeSet.java", "snippet": "public class AttributeSet extends UnidbgStructure {\n\n public AttributeSet(Pointer p) {\n super(p);\n }\n\n public int commonattr; /* common attribute group */\n public int volattr; /* Volume attribute group */\n public int dirattr; /* directory attribute group */\n public int fileattr; /* file attribute group */\n public int forkattr; /* fork attribute group */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"commonattr\", \"volattr\", \"dirattr\", \"fileattr\", \"forkattr\");\n }\n\n}" }, { "identifier": "Dev", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/Dev.java", "snippet": "public class Dev extends UnidbgStructure {\n\n public Dev(Pointer p) {\n super(p);\n }\n\n public int dev;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"dev\");\n }\n\n}" }, { "identifier": "FinderInfo", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/FinderInfo.java", "snippet": "public class FinderInfo extends UnidbgStructure {\n\n public FinderInfo(Pointer p) {\n super(p);\n }\n\n public byte[] finderInfo = new byte[32];\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"finderInfo\");\n }\n\n}" }, { "identifier": "Fsid", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/Fsid.java", "snippet": "public class Fsid extends UnidbgStructure {\n\n public Fsid(Pointer p) {\n super(p);\n }\n\n public int[] val = new int[2];\t/* file system id type */\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"val\");\n }\n\n}" }, { "identifier": "ObjId", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/ObjId.java", "snippet": "public class ObjId extends UnidbgStructure {\n\n public ObjId(Pointer p) {\n super(p);\n }\n\n public int fid_objno;\n public int fid_generation;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"fid_objno\", \"fid_generation\");\n }\n}" }, { "identifier": "ObjType", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/ObjType.java", "snippet": "public class ObjType extends UnidbgStructure {\n\n public ObjType(Pointer p) {\n super(p);\n }\n\n public int type;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"type\");\n }\n\n}" }, { "identifier": "UserAccess", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/UserAccess.java", "snippet": "public class UserAccess extends UnidbgStructure {\n\n public UserAccess(Pointer p) {\n super(p);\n }\n\n public int mode;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"mode\");\n }\n\n}" }, { "identifier": "StatFS", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/StatFS.java", "snippet": "public class StatFS extends UnidbgStructure {\n\n private static final int MFSTYPENAMELEN = 16; /* length of fs type name including null */\n private static final int MAXPATHLEN = 1024; /* max bytes in pathname */\n\n public StatFS(byte[] data) {\n super(data);\n }\n\n public StatFS(Pointer p) {\n super(p);\n }\n\n public int f_bsize; /* fundamental file system block size */\n public int f_iosize; /* optimal transfer block size */\n public long f_blocks; /* total data blocks in file system */\n public long f_bfree; /* free blocks in fs */\n public long f_bavail; /* free blocks avail to non-superuser */\n public long f_files; /* total file nodes in file system */\n public long f_ffree; /* free file nodes in fs */\n\n public long f_fsid; /* file system id */\n public int f_owner; /* user that mounted the filesystem */\n public int f_type; /* type of filesystem */\n public int f_flags; /* copy of mount exported flags */\n public int f_fssubtype; /* fs sub-type (flavor) */\n\n public byte[] f_fstypename = new byte[MFSTYPENAMELEN]; /* fs type name */\n public byte[] f_mntonname = new byte[MAXPATHLEN]; /* directory on which mounted */\n public byte[] f_mntfromname = new byte[MAXPATHLEN]; /* mounted filesystem */\n public int[] f_reserved = new int[8]; /* For future use */\n\n public void setFsTypeName(String fsTypeName) {\n if (fsTypeName == null) {\n throw new NullPointerException();\n }\n byte[] data = fsTypeName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MFSTYPENAMELEN) {\n throw new IllegalStateException(\"Invalid MFSTYPENAMELEN: \" + MFSTYPENAMELEN);\n }\n f_fstypename = Arrays.copyOf(data, MFSTYPENAMELEN);\n }\n\n public void setMntOnName(String mntOnName) {\n if (mntOnName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntOnName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntonname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n public void setMntFromName(String mntFromName) {\n if (mntFromName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntFromName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntfromname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"f_bsize\", \"f_iosize\", \"f_blocks\", \"f_bfree\", \"f_bavail\", \"f_files\", \"f_ffree\", \"f_fsid\", \"f_owner\",\n \"f_type\", \"f_flags\", \"f_fssubtype\", \"f_fstypename\", \"f_mntonname\", \"f_mntfromname\", \"f_reserved\");\n }\n\n}" }, { "identifier": "UnidbgStructure", "path": "unidbg-api/src/main/java/com/github/unidbg/pointer/UnidbgStructure.java", "snippet": "public abstract class UnidbgStructure extends Structure implements PointerArg {\n\n /** Placeholder pointer to help avoid auto-allocation of memory where a\n * Structure needs a valid pointer but want to avoid actually reading from it.\n */\n private static final Pointer PLACEHOLDER_MEMORY = new UnidbgPointer(null, null) {\n @Override\n public UnidbgPointer share(long offset, long sz) { return this; }\n };\n\n public static int calculateSize(Class<? extends UnidbgStructure> type) {\n try {\n Constructor<? extends UnidbgStructure> constructor = type.getConstructor(Pointer.class);\n return constructor.newInstance(PLACEHOLDER_MEMORY).calculateSize(false);\n } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private static class ByteArrayPointer extends UnidbgPointer {\n private final Emulator<?> emulator;\n private final byte[] data;\n public ByteArrayPointer(Emulator<?> emulator, byte[] data) {\n super(emulator, data);\n this.emulator = emulator;\n this.data = data;\n }\n @Override\n public UnidbgPointer share(long offset, long sz) {\n if (offset == 0) {\n return this;\n }\n if (offset > 0 && offset + sz < data.length) {\n if (sz == 0) {\n sz = data.length - offset;\n }\n byte[] tmp = new byte[(int) sz];\n System.arraycopy(data, (int) offset, tmp, 0, (int) sz);\n return new ByteArrayPointer(emulator, tmp);\n }\n throw new UnsupportedOperationException(\"offset=0x\" + Long.toHexString(offset) + \", sz=\" + sz);\n }\n }\n\n protected UnidbgStructure(Emulator<?> emulator, byte[] data) {\n this(new ByteArrayPointer(emulator, data));\n }\n\n protected UnidbgStructure(byte[] data) {\n this(null, data);\n }\n\n protected UnidbgStructure(Pointer p) {\n super(p);\n\n checkPointer(p);\n }\n\n private void checkPointer(Pointer p) {\n if (p == null) {\n throw new NullPointerException(\"p is null\");\n }\n if (!(p instanceof UnidbgPointer) && !isPlaceholderMemory(p)) {\n throw new IllegalArgumentException(\"p is NOT UnidbgPointer\");\n }\n }\n\n @Override\n protected int getNativeSize(Class<?> nativeType, Object value) {\n if (Pointer.class.isAssignableFrom(nativeType)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeSize(nativeType, value);\n }\n\n @Override\n protected int getNativeAlignment(Class<?> type, Object value, boolean isFirstElement) {\n if (Pointer.class.isAssignableFrom(type)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeAlignment(type, value, isFirstElement);\n }\n\n private boolean isPlaceholderMemory(Pointer p) {\n return \"native@0x0\".equals(p.toString());\n }\n\n public void pack() {\n super.write();\n }\n\n public void unpack() {\n super.read();\n }\n\n /**\n * @param debug If true, will include a native memory dump of the\n * Structure's backing memory.\n * @return String representation of this object.\n */\n public String toString(boolean debug) {\n return toString(0, true, debug);\n }\n\n private String format(Class<?> type) {\n String s = type.getName();\n int dot = s.lastIndexOf(\".\");\n return s.substring(dot + 1);\n }\n\n private String toString(int indent, boolean showContents, boolean dumpMemory) {\n ensureAllocated();\n String LS = System.getProperty(\"line.separator\");\n String name = format(getClass()) + \"(\" + getPointer() + \")\";\n if (!(getPointer() instanceof Memory)) {\n name += \" (\" + size() + \" bytes)\";\n }\n StringBuilder prefix = new StringBuilder();\n for (int idx=0;idx < indent;idx++) {\n prefix.append(\" \");\n }\n StringBuilder contents = new StringBuilder(LS);\n if (!showContents) {\n contents = new StringBuilder(\"...}\");\n }\n else for (Iterator<StructField> i = fields().values().iterator(); i.hasNext();) {\n StructField sf = i.next();\n Object value = getFieldValue(sf.field);\n String type = format(sf.type);\n String index = \"\";\n contents.append(prefix);\n if (sf.type.isArray() && value != null) {\n type = format(sf.type.getComponentType());\n index = \"[\" + Array.getLength(value) + \"]\";\n }\n contents.append(String.format(\" %s %s%s@0x%X\", type, sf.name, index, sf.offset));\n if (value instanceof UnidbgStructure) {\n value = ((UnidbgStructure)value).toString(indent + 1, !(value instanceof Structure.ByReference), dumpMemory);\n }\n contents.append(\"=\");\n if (value instanceof Long) {\n contents.append(String.format(\"0x%08X\", value));\n }\n else if (value instanceof Integer) {\n contents.append(String.format(\"0x%04X\", value));\n }\n else if (value instanceof Short) {\n contents.append(String.format(\"0x%02X\", value));\n }\n else if (value instanceof Byte) {\n contents.append(String.format(\"0x%01X\", value));\n }\n else if (value instanceof byte[]) {\n contents.append(Hex.encodeHexString((byte[]) value));\n }\n else {\n contents.append(String.valueOf(value).trim());\n }\n contents.append(LS);\n if (!i.hasNext())\n contents.append(prefix).append(\"}\");\n }\n if (indent == 0 && dumpMemory) {\n final int BYTES_PER_ROW = 4;\n contents.append(LS).append(\"memory dump\").append(LS);\n byte[] buf = getPointer().getByteArray(0, size());\n for (int i=0;i < buf.length;i++) {\n if ((i % BYTES_PER_ROW) == 0) contents.append(\"[\");\n if (buf[i] >=0 && buf[i] < 16)\n contents.append(\"0\");\n contents.append(Integer.toHexString(buf[i] & 0xff));\n if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1)\n contents.append(\"]\").append(LS);\n }\n contents.append(\"]\");\n }\n return name + \" {\" + contents;\n }\n\n /** Obtain the value currently in the Java field. Does not read from\n * native memory.\n * @param field field to look up\n * @return current field value (Java-side only)\n */\n private Object getFieldValue(Field field) {\n try {\n return field.get(this);\n }\n catch (Exception e) {\n throw new Error(\"Exception reading field '\" + field.getName() + \"' in \" + getClass(), e);\n }\n }\n\n private static final Field FIELD_STRUCT_FIELDS;\n\n static {\n try {\n FIELD_STRUCT_FIELDS = Structure.class.getDeclaredField(\"structFields\");\n FIELD_STRUCT_FIELDS.setAccessible(true);\n } catch (NoSuchFieldException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Return all fields in this structure (ordered). This represents the\n * layout of the structure, and will be shared among Structures of the\n * same class except when the Structure can have a variable size.\n * NOTE: {@link #ensureAllocated()} <em>must</em> be called prior to\n * calling this method.\n * @return {@link Map} of field names to field representations.\n */\n @SuppressWarnings(\"unchecked\")\n private Map<String, StructField> fields() {\n try {\n return (Map<String, StructField>) FIELD_STRUCT_FIELDS.get(this);\n } catch (IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }\n}" }, { "identifier": "UnixEmulator", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/UnixEmulator.java", "snippet": "public interface UnixEmulator {\n\n int EPERM = 1; /* Operation not permitted */\n int ENOENT = 2; /* No such file or directory */\n int ESRCH = 3; /* No such process */\n int EINTR = 4; /* Interrupted system call */\n int EBADF = 9; /* Bad file descriptor */\n int EAGAIN = 11; /* Resource temporarily unavailable */\n int ENOMEM = 12; /* Cannot allocate memory */\n int EACCES = 13; /* Permission denied */\n int EFAULT = 14; /* Bad address */\n int EEXIST = 17; /* File exists */\n int ENOTDIR = 20; /* Not a directory */\n int EINVAL = 22; /* Invalid argument */\n int ENOTTY = 25; /* Inappropriate ioctl for device */\n int ENOSYS = 38; /* Function not implemented */\n int ENOATTR = 93; /* Attribute not found */\n int EOPNOTSUPP = 95; /* Operation not supported on transport endpoint */\n int EAFNOSUPPORT = 97; /* Address family not supported by protocol family */\n int EADDRINUSE = 98; /* Address already in use */\n int ECONNREFUSED = 111; /* Connection refused */\n\n}" }, { "identifier": "TimeSpec32", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/struct/TimeSpec32.java", "snippet": "public class TimeSpec32 extends TimeSpec {\n\n public TimeSpec32(Pointer p) {\n super(p);\n }\n\n public int tv_sec; // unsigned long\n public int tv_nsec; // long\n\n @Override\n public long getTvSec() {\n return tv_sec;\n }\n\n @Override\n public long getTvNsec() {\n return tv_nsec;\n }\n\n @Override\n protected void setTv(long tvSec, long tvNsec) {\n this.tv_sec = (int) tvSec;\n this.tv_nsec = (int) tvNsec;\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"tv_sec\", \"tv_nsec\");\n }\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.github.unidbg.Emulator; import com.github.unidbg.file.BaseFileIO; import com.github.unidbg.file.UnidbgFileFilter; import com.github.unidbg.ios.file.DirectoryFileIO; import com.github.unidbg.ios.struct.attr.AttrList; import com.github.unidbg.ios.struct.attr.AttrReference; import com.github.unidbg.ios.struct.attr.AttributeSet; import com.github.unidbg.ios.struct.attr.Dev; import com.github.unidbg.ios.struct.attr.FinderInfo; import com.github.unidbg.ios.struct.attr.Fsid; import com.github.unidbg.ios.struct.attr.ObjId; import com.github.unidbg.ios.struct.attr.ObjType; import com.github.unidbg.ios.struct.attr.UserAccess; import com.github.unidbg.ios.struct.kernel.StatFS; import com.github.unidbg.pointer.UnidbgStructure; import com.github.unidbg.unix.UnixEmulator; import com.github.unidbg.unix.struct.TimeSpec32; import com.sun.jna.Pointer; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List;
7,154
package com.github.unidbg.file.ios; public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO { private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class); public static File createAttrFile(File dest) { if (!dest.exists()) { throw new IllegalStateException("dest=" + dest); } File file; if (dest.isDirectory()) {
package com.github.unidbg.file.ios; public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO { private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class); public static File createAttrFile(File dest) { if (!dest.exists()) { throw new IllegalStateException("dest=" + dest); } File file; if (dest.isDirectory()) {
file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + ".json");
2
2023-10-17 06:13:28+00:00
8k
EyeOfDarkness/FlameOut
src/flame/graphics/VaporizeBatch.java
[ { "identifier": "Disintegration", "path": "src/flame/effects/Disintegration.java", "snippet": "public class Disintegration implements Poolable{\n float[] xs, ys;\n int width, height;\n float drawWidth, drawHeight;\n TextureRegion region;\n int uses = 0;\n\n public float z = Layer.flyingUnit;\n public Color drawnColor = Color.white.cpy(), scorchColor = Pal.rubble.cpy();\n\n static Pool<Disintegration> pool = new BasicPool<>(Disintegration::new);\n static int maxDimension = 64;\n static Point2 tmpPoint = new Point2();\n static FloatSeq fseq = new FloatSeq();\n static int[] arr = {\n 0, 0,\n 1, 0,\n 1, 1,\n 0, 1\n };\n\n public Disintegration(){}\n\n public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, Cons<DisintegrationEntity> cons){\n int modW = (int)((5f / 320f) * Math.abs(width / Draw.scl));\n int modH = (int)((5f / 320f) * Math.abs(height / Draw.scl));\n return generate(region, x, y, rotation, width, height, modW, modH, cons);\n }\n\n public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, int iwidth, int iheight, Cons<DisintegrationEntity> cons){\n //int modW = (int)((20f / 320f) * Math.abs(width / Draw.scl));\n //int modH = (int)((20f / 320f) * Math.abs(height / Draw.scl));\n\n float cos = Mathf.cosDeg(rotation);\n float sin = Mathf.sinDeg(rotation);\n\n Disintegration dis = pool.obtain();\n dis.set(iwidth, iheight);\n dis.region = region;\n dis.drawWidth = width;\n dis.drawHeight = height;\n dis.uses = 0;\n\n int w = dis.width, h = dis.height;\n for(int ix = 0; ix < w - 1; ix++){\n for(int iy = 0; iy < h - 1; iy++){\n float ox = 0f, oy = 0f;\n for(int i = 0; i < 8; i += 2){\n int bx = ix + arr[i];\n int by = iy + arr[i + 1];\n int pos = dis.toPos(bx, by);\n\n ox += dis.xs[pos];\n oy += dis.ys[pos];\n }\n ox /= 4f;\n oy /= 4f;\n\n float rx = (ox - 0.5f) * width;\n float ry = (oy - 0.5f) * height;\n\n float wx = (rx * cos - ry * sin) + x;\n float wy = (rx * sin + ry * cos) + y;\n\n DisintegrationEntity de = DisintegrationEntity.create();\n de.source = dis;\n de.x = wx;\n de.y = wy;\n de.rotation = rotation;\n de.idx = dis.toPos(ix, iy);\n de.offsetX = ox;\n de.offsetY = oy;\n de.lifetime = 6f * 60f;\n\n cons.get(de);\n\n de.add();\n dis.uses++;\n }\n }\n\n return dis;\n }\n\n public void set(int width, int height){\n width = Mathf.clamp(width, 3, maxDimension);\n height = Mathf.clamp(height, 3, maxDimension);\n int size = width * height;\n\n this.width = width;\n this.height = height;\n\n if(xs == null || xs.length != size) xs = new float[size];\n if(ys == null || ys.length != size) ys = new float[size];\n\n for(int x = 0; x < width; x++){\n for(int y = 0; y < height; y++){\n float fx = x / (width - 1f);\n float fy = y / (height - 1f);\n int idx = x + y * width;\n\n if(x > 0 && x < (width - 1)){\n fx += Mathf.range(0.1f, 0.4f) / (width - 1f);\n }\n if(y > 0 && y < (height - 1)){\n fy += Mathf.range(0.1f, 0.4f) / (height - 1f);\n }\n\n xs[idx] = fx;\n ys[idx] = fy;\n }\n }\n }\n\n Point2 getPos(int pos){\n tmpPoint.x = pos % width;\n tmpPoint.y = pos / width;\n return tmpPoint;\n }\n int toPos(int x, int y){\n return x + y * width;\n }\n\n @Override\n public void reset(){\n //xs = ys = null;\n width = height = 0;\n drawWidth = drawHeight = 0f;\n drawnColor.set(Color.white);\n scorchColor.set(Pal.rubble);\n region = Core.atlas.white();\n uses = 0;\n z = Layer.flyingUnit;\n }\n\n public static class DisintegrationEntity extends DrawEntity implements Poolable{\n public Disintegration source;\n int idx = 0;\n\n float rotation = 0f;\n float offsetX, offsetY;\n\n public float vx, vy, vr, drag = 0.05f;\n public float time, lifetime;\n public float zOverride = -1f;\n public boolean disintegrating = false;\n\n static DisintegrationEntity create(){\n return Pools.obtain(DisintegrationEntity.class, DisintegrationEntity::new);\n }\n\n public float getSize(){\n return Math.max(source.drawWidth / (source.width - 1), source.drawHeight / (source.height - 1)) / 2f;\n }\n\n @Override\n public void update(){\n x += vx * Time.delta;\n y += vy * Time.delta;\n rotation += vr * Time.delta;\n\n float dt = 1f - drag * Time.delta;\n vx *= dt;\n vy *= dt;\n //vr *= dt;\n\n if((time += Time.delta) >= lifetime){\n remove();\n }\n }\n\n @Override\n public void draw(){\n float cos = Mathf.cosDeg(rotation);\n float sin = Mathf.sinDeg(rotation);\n\n TextureRegion region = source.region;\n float[] xs = source.xs, ys = source.ys;\n float scl = 1f;\n\n Point2 pos = source.getPos(idx);\n\n if(disintegrating){\n Tmp.c1.set(source.drawnColor).lerp(source.scorchColor, Mathf.curve(time / lifetime, 0f, 0.75f));\n scl = Interp.pow5Out.apply(1f - Mathf.clamp(time / lifetime));\n }else{\n Tmp.c1.set(source.drawnColor).a(1f - Mathf.curve(time / lifetime, 0.7f, 1f));\n }\n\n float color = Tmp.c1.toFloatBits();\n float mcolr = Color.clearFloatBits;\n\n fseq.clear();\n for(int i = 0; i < 8; i += 2){\n int sx = pos.x + arr[i];\n int sy = pos.y + arr[i + 1];\n\n int ps = source.toPos(sx, sy);\n float fx = xs[ps];\n float fy = ys[ps];\n\n float ox = (fx - offsetX) * source.drawWidth * scl;\n float oy = (fy - offsetY) * source.drawHeight * scl;\n\n float tx = (ox * cos - oy * sin) + x;\n float ty = (ox * sin + oy * cos) + y;\n\n float u = Mathf.lerp(region.u, region.u2, xs[ps]);\n float v = Mathf.lerp(region.v2, region.v, ys[ps]);\n\n fseq.addAll(tx, ty, color, u, v, mcolr);\n }\n Draw.z(zOverride != -1f ? zOverride : source.z);\n Draw.vert(region.texture, fseq.items, 0, fseq.size);\n }\n\n @Override\n public void reset(){\n idx = 0;\n time = 0f;\n lifetime = 0f;\n vx = vy = vr = 0f;\n zOverride = -1f;\n drag = 0.05f;\n source = null;\n disintegrating = false;\n }\n\n @Override\n protected void removeGroup(){\n super.removeGroup();\n Groups.queueFree(this);\n source.uses--;\n if(source.uses <= 0){\n idx = -1;\n pool.free(source);\n }\n }\n }\n}" }, { "identifier": "RenderGroupEntity", "path": "src/flame/entities/RenderGroupEntity.java", "snippet": "public class RenderGroupEntity extends DrawEntity implements Poolable{\n float bounds = 0f;\n Seq<DrawnRegion> regions = new Seq<>();\n\n static RenderGroupEntity active;\n static float minX, minY, maxX, maxY;\n static float[] tmpVert = new float[4 * 6];\n static Pool<DrawnRegion> regionPool = new BasicPool<>(DrawnRegion::new);\n\n public static void capture(){\n if(active != null) return;\n\n minX = 9999999f;\n minY = 9999999f;\n maxX = -9999999f;\n maxY = -9999999f;\n\n active = Pools.obtain(RenderGroupEntity.class, RenderGroupEntity::new);\n }\n public static void end(){\n if(active == null || active.regions.isEmpty()){\n active = null;\n return;\n }\n\n active.x = (minX + maxX) / 2;\n active.y = (minY + maxY) / 2;\n\n active.bounds = Math.max(maxX - minX, maxY - minY) * 2f;\n\n active.add();\n active = null;\n }\n static void updateBounds(float x, float y){\n minX = Math.min(x, minX);\n minY = Math.min(y, minY);\n\n maxX = Math.max(x, maxX);\n maxY = Math.max(y, maxY);\n }\n\n public static DrawnRegion draw(Blending blending, float z, Texture texture, float[] verticies, int offset){\n DrawnRegion r = regionPool.obtain();\n r.blending = blending;\n r.z = z;\n r.setVerticies(texture, verticies, offset);\n\n if(active != null){\n active.regions.add(r);\n }\n return r;\n }\n public static DrawnRegion draw(Blending blending, float z, TextureRegion region, float x, float y, float originX, float originY, float width, float height, float rotation, float color){\n DrawnRegion r = regionPool.obtain();\n r.blending = blending;\n r.z = z;\n r.setRegion(region, x, y, originX, originY, width, height, rotation, color);\n\n if(active != null){\n active.regions.add(r);\n }\n\n return r;\n }\n\n @Override\n public void update(){\n regions.removeAll(r -> {\n r.update();\n if(r.time >= r.lifetime){\n regionPool.free(r);\n }\n return r.time >= r.lifetime;\n });\n if(regions.isEmpty()){\n remove();\n }\n }\n\n @Override\n public float clipSize(){\n return bounds;\n }\n\n @Override\n public void draw(){\n for(DrawnRegion r : regions){\n r.draw();\n }\n }\n\n @Override\n protected void removeGroup(){\n super.removeGroup();\n Groups.queueFree(this);\n }\n\n @Override\n public void reset(){\n bounds = 0f;\n regions.clear();\n }\n\n public static class DrawnRegion implements Poolable{\n public float[] data = new float[4 * 6];\n public float z;\n public Texture texture;\n public Blending blending = Blending.normal;\n\n public float time, lifetime;\n public float fadeCurveIn = 0f, fadeCurveOut = 1f;\n\n void update(){\n time += Time.delta;\n }\n\n public void setVerticies(Texture texture, float[] verticies, int offset){\n this.texture = texture;\n System.arraycopy(verticies, offset, data, 0, data.length);\n if(active != null){\n for(int i = 0; i < 24; i += 6){\n updateBounds(data[i], data[i + 1]);\n\n data[i + 5] = Color.clearFloatBits;\n }\n }\n }\n\n public void setRegion(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float rotation, float color){\n float[] vertices = data;\n\n float mixColor = Color.clearFloatBits;\n\n float worldOriginX = x + originX;\n float worldOriginY = y + originY;\n float fx = -originX;\n float fy = -originY;\n float fx2 = width - originX;\n float fy2 = height - originY;\n\n float cos = Mathf.cosDeg(rotation);\n float sin = Mathf.sinDeg(rotation);\n\n float x1 = cos * fx - sin * fy + worldOriginX;\n float y1 = sin * fx + cos * fy + worldOriginY;\n float x2 = cos * fx - sin * fy2 + worldOriginX;\n float y2 = sin * fx + cos * fy2 + worldOriginY;\n float x3 = cos * fx2 - sin * fy2 + worldOriginX;\n float y3 = sin * fx2 + cos * fy2 + worldOriginY;\n float x4 = x1 + (x3 - x2);\n float y4 = y3 - (y2 - y1);\n\n float u = region.u;\n float v = region.v2;\n float u2 = region.u2;\n float v2 = region.v;\n\n texture = region.texture;\n\n if(active != null){\n updateBounds(x1, y1);\n updateBounds(x2, y2);\n updateBounds(x3, y3);\n updateBounds(x4, y4);\n }\n\n vertices[0] = x1;\n vertices[1] = y1;\n vertices[2] = color;\n vertices[3] = u;\n vertices[4] = v;\n vertices[5] = mixColor;\n\n vertices[6] = x2;\n vertices[7] = y2;\n vertices[8] = color;\n vertices[9] = u;\n vertices[10] = v2;\n vertices[11] = mixColor;\n\n vertices[12] = x3;\n vertices[13] = y3;\n vertices[14] = color;\n vertices[15] = u2;\n vertices[16] = v2;\n vertices[17] = mixColor;\n\n vertices[18] = x4;\n vertices[19] = y4;\n vertices[20] = color;\n vertices[21] = u2;\n vertices[22] = v;\n vertices[23] = mixColor;\n }\n\n @Override\n public void reset(){\n time = 0f;\n lifetime = 0f;\n fadeCurveIn = 0f;\n fadeCurveOut = 1f;\n }\n\n void draw(){\n float fin = 1f - Mathf.curve(time / lifetime, fadeCurveIn, fadeCurveOut);\n\n Draw.z(z);\n Draw.blend(blending);\n\n System.arraycopy(data, 0, tmpVert, 0, 24);\n\n if(fin < 0.999f){\n for(int i = 0; i < 24; i += 6){\n float col = tmpVert[i + 2];\n Tmp.c1.abgr8888(col);\n Tmp.c1.a(Tmp.c1.a * fin);\n tmpVert[i + 2] = Tmp.c1.toFloatBits();\n }\n }\n Draw.vert(texture, tmpVert, 0, data.length);\n\n Draw.blend();\n }\n }\n}" }, { "identifier": "CutBatch", "path": "src/flame/graphics/CutBatch.java", "snippet": "public class CutBatch extends Batch{\n public Effect explosionEffect;\n public Cons<Severation> cutHandler;\n static Seq<Severation> returnEntities = new Seq<>();\n\n public Seq<Severation> switchBatch(Runnable run){\n Batch last = Core.batch;\n GL20 lgl = Core.gl;\n Core.batch = this;\n Core.gl = FragmentationBatch.mock;\n Lines.useLegacyLine = true;\n returnEntities.clear();\n\n run.run();\n\n Lines.useLegacyLine = false;\n Core.batch = last;\n Core.gl = lgl;\n\n return returnEntities;\n }\n\n @Override\n protected void setMixColor(Color tint){\n\n }\n @Override\n protected void setMixColor(float r, float g, float b, float a){\n\n }\n @Override\n protected void setPackedMixColor(float packedColor){\n\n }\n\n @Override\n protected void draw(Texture texture, float[] spriteVertices, int offset, int count){}\n\n @Override\n protected void draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float rotation){\n float midX = (width / 2f);\n float midY = (height / 2f);\n\n float cos = Mathf.cosDeg(rotation);\n float sin = Mathf.sinDeg(rotation);\n float dx = midX - originX;\n float dy = midY - originY;\n\n float bx = (cos * dx - sin * dy) + (x + originX);\n float by = (sin * dx + cos * dy) + (y + originY);\n\n if(color.a <= 0.9f || region == FragmentationBatch.updateCircle() || blending != Blending.normal || region == Core.atlas.white() || !region.found()){\n RejectedRegion r = new RejectedRegion();\n r.region = region;\n r.blend = blending;\n r.z = z;\n r.width = width;\n r.height = height;\n\n FlameFX.rejectedRegion.at(bx, by, rotation, color, r);\n return;\n }\n Severation c = Severation.generate(region, bx, by, width, height, rotation);\n c.color = colorPacked;\n c.z = z;\n if(explosionEffect != null){\n c.explosionEffect = explosionEffect;\n }\n if(cutHandler != null){\n cutHandler.get(c);\n }\n returnEntities.add(c);\n }\n\n @Override\n protected void flush(){\n\n }\n\n @Override\n protected void setShader(Shader shader, boolean apply){}\n\n public static class RejectedRegion{\n public TextureRegion region;\n public Blending blend = Blending.normal;\n public float width, height, z;\n }\n}" } ]
import arc.*; import arc.func.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.graphics.gl.*; import arc.math.*; import arc.math.geom.*; import arc.util.*; import flame.effects.*; import flame.effects.Disintegration.*; import flame.entities.*; import flame.entities.RenderGroupEntity.*; import flame.graphics.CutBatch.*;
4,923
package flame.graphics; public class VaporizeBatch extends Batch{ public VaporizeHandler cons; public SpriteHandler spriteHandler; public Cons<Disintegration> discon; final static Rect tr = new Rect(); public void switchBatch(Runnable drawer, SpriteHandler handler, VaporizeHandler cons){ Batch last = Core.batch; GL20 lgl = Core.gl; Core.batch = this; Core.gl = FragmentationBatch.mock; Lines.useLegacyLine = true;
package flame.graphics; public class VaporizeBatch extends Batch{ public VaporizeHandler cons; public SpriteHandler spriteHandler; public Cons<Disintegration> discon; final static Rect tr = new Rect(); public void switchBatch(Runnable drawer, SpriteHandler handler, VaporizeHandler cons){ Batch last = Core.batch; GL20 lgl = Core.gl; Core.batch = this; Core.gl = FragmentationBatch.mock; Lines.useLegacyLine = true;
RenderGroupEntity.capture();
1
2023-10-18 08:41:59+00:00
8k
ItzGreenCat/SkyImprover
src/main/java/me/greencat/skyimprover/SkyImprover.java
[ { "identifier": "Config", "path": "src/main/java/me/greencat/skyimprover/config/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashEnable = true;\n @Entry(category = \"render\")\n public static boolean damageSplashCompact = true;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 5.0F)\n public static float damageSplashOffset = 2.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 10.0F)\n public static float damageSplashDuration = 3.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 2.0F)\n public static float damageSplashAnimationSpeed = 0.3F;\n\n @Comment(category = \"misc\")\n public static Comment rainTimer;\n @Entry(category = \"misc\")\n public static boolean rainTimerEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetY = 0.3F;\n @Comment(category = \"misc\")\n public static Comment ferocityCount;\n @Entry(category = \"misc\")\n public static boolean ferocityCountEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetY = 0.4F;\n\n @Comment(category = \"dungeon\")\n public static Comment m3FreezeHelper;\n @Entry(category = \"dungeon\")\n public static boolean m3FreezeHelperEnable = true;\n\n @Comment(category = \"dungeon\")\n public static Comment dungeonDeathMessage;\n @Entry(category = \"dungeon\")\n public static boolean dungeonDeathMessageEnable = true;\n @Entry(category = \"dungeon\")\n public static String dungeonDeathMessageContent = \"BOOM!\";\n @Comment(category = \"dungeon\")\n public static Comment kuudraHelper;\n @Entry(category = \"dungeon\")\n public static boolean kuudraHelperEnable = true;\n}" }, { "identifier": "FeatureLoader", "path": "src/main/java/me/greencat/skyimprover/feature/FeatureLoader.java", "snippet": "public class FeatureLoader {\n public static void load(Class<? extends Module> clazz){\n try {\n clazz.newInstance().registerEvent();\n LogUtils.getLogger().info(\"[SkyImprover] Registering Module:\" + clazz.getSimpleName());\n } catch(Exception e){\n throw new RuntimeException(e);\n }\n }\n public static void loadAll(String packa9e){\n ClassScanner.getClzFromPkg(packa9e).stream().filter(it -> Arrays.stream(it.getInterfaces()).anyMatch(in7erface -> in7erface.getName().equals(Module.class.getName()))).forEach(it -> load((Class<? extends Module>) it));\n }\n}" }, { "identifier": "DamageSplash", "path": "src/main/java/me/greencat/skyimprover/feature/damageSplash/DamageSplash.java", "snippet": "public class DamageSplash implements Module {\n private static final Pattern pattern = Pattern.compile(\"[✧✯]?(\\\\d{1,3}(?:,\\\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)\");\n private static final Deque<RenderInformation> damages = new LinkedList<>();\n private static final DecimalFormat decimalFormat = new DecimalFormat(\"0.00\");\n private static final Random random = new Random();\n @Override\n public void registerEvent() {\n RenderLivingEntityPreEvent.EVENT.register(DamageSplash::onRenderEntity);\n WorldRenderEvents.LAST.register(DamageSplash::onRenderWorld);\n }\n public static boolean onRenderEntity(LivingEntity entity){\n if(!Config.damageSplashEnable){\n return true;\n }\n if(entity instanceof ArmorStandEntity && entity.hasCustomName()){\n String customName = entity.getCustomName().getString();\n Matcher matcher = pattern.matcher(customName == null ? \"\" : customName);\n if(matcher.matches() && customName != null){\n String damage = customName.replaceAll( \"[^\\\\d]\", \"\");\n if(Config.damageSplashCompact){\n try {\n int damageInteger = Integer.parseInt(damage);\n if (damageInteger >= 1000 && damageInteger < 1000000) {\n double damageDouble = damageInteger / 1000.0D;\n damage = decimalFormat.format(damageDouble) + \"K\";\n } else if (damageInteger >= 1000000 && damageInteger < 1000000000) {\n double damageDouble = damageInteger / 1000000.0D;\n damage = decimalFormat.format(damageDouble) + \"M\";\n } else if (damageInteger >= 1000000000) {\n double damageDouble = damageInteger / 1000000000.0D;\n damage = decimalFormat.format(damageDouble) + \"B\";\n }\n } catch(Exception ignored){}\n }\n damages.add(new RenderInformation(entity.getX() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset, entity.getY() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset, entity.getZ() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset,damage,new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255))));\n if (MinecraftClient.getInstance().world != null) {\n MinecraftClient.getInstance().world.removeEntity(entity.getId(), Entity.RemovalReason.UNLOADED_WITH_PLAYER);\n }\n return false;\n }\n }\n return true;\n }\n public static void onRenderWorld(WorldRenderContext wrc){\n List<RenderInformation> removeList = new ArrayList<>();\n for(RenderInformation info : damages){\n Vec3d pos = new Vec3d(info.x, info.y,info.z);\n float scaling = (float)Math.max(2,Math.log(pos.distanceTo(MinecraftClient.getInstance().player.getPos()) * 3));\n TextRenderUtils.renderText(wrc,Text.literal(info.message).fillStyle(Style.EMPTY.withColor(info.color.getRGB())),pos,System.currentTimeMillis() - info.startTime <= Config.damageSplashAnimationSpeed * 1000 ? (System.currentTimeMillis() - info.startTime) / (Config.damageSplashAnimationSpeed * 1000) * scaling:scaling,true);\n if(System.currentTimeMillis() - info.startTime >= Config.damageSplashDuration * 1000){\n removeList.add(info);\n }\n }\n if(!removeList.isEmpty()) {\n damages.removeAll(removeList);\n }\n }\n static class RenderInformation{\n double x;\n double y;\n double z;\n String message;\n Color color;\n long startTime;\n public RenderInformation(double x,double y,double z,String message,Color color){\n this.x = x;\n this.y = y;\n this.z = z;\n this.message = message;\n this.startTime = System.currentTimeMillis();\n this.color = color;\n }\n }\n}" }, { "identifier": "DungeonDeathMessage", "path": "src/main/java/me/greencat/skyimprover/feature/dungeonDeathMessage/DungeonDeathMessage.java", "snippet": "public class DungeonDeathMessage implements Module {\n @Override\n public void registerEvent() {\n ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat);\n }\n\n private static boolean onChat(Text text, boolean overlay) {\n if(!Config.dungeonDeathMessageEnable){\n return true;\n }\n LocationUtils.update();\n if(!LocationUtils.isInDungeons){\n return true;\n }\n String message = text.getString();\n if(message.contains(\"☠\") && !message.contains(\"Crit Damage\")){\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.networkHandler.sendChatMessage(Config.dungeonDeathMessageContent);\n }\n }\n return true;\n }\n}" }, { "identifier": "KuudraHelper", "path": "src/main/java/me/greencat/skyimprover/feature/kuudraHelper/KuudraHelper.java", "snippet": "public class KuudraHelper implements Module {\n public static long lastRefresh = 0L;\n @Override\n public void registerEvent() {\n //SUPPLIES\n //BRING SUPPLY CHEST HERE\n //SUPPLIES RECEIVED\n //SUPPLY PILE\n //PROGRESS:\n //FUEL CELL\n WorldRenderEvents.LAST.register(KuudraHelper::onRender);\n }\n\n private static void onRender(WorldRenderContext worldRenderContext) {\n if(System.currentTimeMillis() - lastRefresh >= 5000){\n lastRefresh = System.currentTimeMillis();\n LocationUtils.update();\n }\n if(!LocationUtils.isInKuudra){\n return;\n }\n if(!Config.kuudraHelperEnable){\n return;\n }\n MinecraftClient client = MinecraftClient.getInstance();\n ClientWorld world = client.world;\n ClientPlayerEntity player = MinecraftClient.getInstance().player;\n if(world == null || player == null){\n return;\n }\n for(Entity entity : world.getEntities()){\n if(!(entity instanceof ArmorStandEntity armorStand)){\n continue;\n }\n if(!armorStand.hasCustomName()){\n continue;\n }\n if(armorStand.getCustomName() != null) {\n String name = armorStand.getCustomName().getString();\n if(name.contains(\"SUPPLIES\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.RED);\n }\n if(name.contains(\"BRING SUPPLY CHEST HERE\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.WHITE);\n }\n if(name.contains(\"SUPPLIES RECEIVED\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.GREEN);\n }\n if(name.contains(\"PROGRESS:\")){\n float scaling = (float)Math.max(2,Math.log(armorStand.getPos().distanceTo(MinecraftClient.getInstance().player.getPos()) * 5));\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.CYAN);\n TextRenderUtils.renderText(worldRenderContext, Text.literal(name.replace(\"PROGRESS:\",\"\")).formatted(Formatting.AQUA),armorStand.getPos(),scaling,true);\n }\n if(name.contains(\"FUEL CELL\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.YELLOW);\n }\n }\n }\n }\n\n}" }, { "identifier": "M3FreezeHelper", "path": "src/main/java/me/greencat/skyimprover/feature/m3Freeze/M3FreezeHelper.java", "snippet": "public class M3FreezeHelper implements Module {\n private static long lastReceiveTargetMessage = 0L;\n private static boolean isSend = true;\n @Override\n public void registerEvent() {\n ClientReceiveMessageEvents.ALLOW_GAME.register(M3FreezeHelper::onChat);\n ClientTickEvents.END_CLIENT_TICK.register(M3FreezeHelper::onTick);\n }\n\n private static void onTick(MinecraftClient client) {\n if(System.currentTimeMillis() - lastReceiveTargetMessage >= 5250 && !isSend){\n isSend = true;\n MinecraftClient.getInstance().inGameHud.setTitle(Text.literal(Formatting.RED + \"Freeze!\"));\n }\n }\n\n public static boolean onChat(Text text, boolean overlay){\n if(!Config.m3FreezeHelperEnable){\n return true;\n }\n String message = text.getString();\n if(message.contains(\"You found my Guardians' one weakness?\")){\n lastReceiveTargetMessage = System.currentTimeMillis();\n isSend = false;\n }\n return true;\n }\n\n}" }, { "identifier": "RainTimer", "path": "src/main/java/me/greencat/skyimprover/feature/rainTimer/RainTimer.java", "snippet": "public class RainTimer implements Module {\n private static final SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssXXX\");\n private static long lastRefresh = 0L;\n\n private static final int cooldown = 2400;\n private static final int duration = 1200;\n private static final int thunderstormInterval = 3;\n\n private static String displayTimeLeft = secsToTime(0);\n private static String displayNextRain = secsToTime(0);\n\n private static boolean netxIsStormCache;\n private static boolean thunderStormNowCache;\n private static boolean rainNowCache;\n\n @Override\n public void registerEvent() {\n HudRenderCallback.EVENT.register(RainTimer::onOverlayRendering);\n }\n public static void onOverlayRendering(DrawContext context,float tick){\n if(!Config.rainTimerEnable){\n return;\n }\n Text displayText = null;\n if(netxIsStormCache){\n displayText = Text.translatable(\"rainTimer.hud.NextThunder\").append(Text.literal(\": \" + displayNextRain + \"⚡\")).fillStyle(Style.EMPTY.withColor(Formatting.GOLD));\n } else if(thunderStormNowCache){\n displayText = Text.translatable(\"rainTimer.hud.rainLeft\").append(Text.literal(\": \" + displayTimeLeft + \"⚡\")).fillStyle(Style.EMPTY.withColor(Formatting.GOLD));\n } else if(rainNowCache){\n displayText = Text.translatable(\"rainTimer.hud.rainLeft\").append(Text.literal(\": \" + displayTimeLeft)).fillStyle(Style.EMPTY.withColor(Formatting.AQUA));\n } else {\n displayText = Text.translatable(\"rainTimer.hud.NextRain\").append(Text.literal(\": \" + displayNextRain));\n }\n TextRenderUtils.renderHUDText(context,(int)(context.getScaledWindowWidth() * Config.rainTimerGuiOffsetX), (int)(context.getScaledWindowHeight() * Config.rainTimerGuiOffsetY),displayText);\n if(System.currentTimeMillis() - lastRefresh <= 1000L){\n return;\n }\n lastRefresh = System.currentTimeMillis();\n\n long timestamp = (long) Math.floor(System.currentTimeMillis() / 1000.0D);\n long skyblockAge = (timestamp - 1560275700);\n\n long thunderstorm = skyblockAge % ((cooldown + duration) * thunderstormInterval);\n long rain = skyblockAge % (cooldown + duration);\n\n boolean rainNow = false;\n if (cooldown <= rain) {\n rainNow = true;\n long timeLeft = (cooldown + duration) - rain;\n displayTimeLeft = secsToTime(timeLeft);\n displayNextRain = secsToTime(timeLeft + cooldown);\n } else {\n rainNow = false;\n displayNextRain = secsToTime(cooldown - rain);\n }\n boolean thunderStormNow = false;\n boolean netxIsStorm = false;\n if ((cooldown <= thunderstorm) && (thunderstorm < (cooldown + duration))) {\n thunderStormNow = true;\n long timeLeft = (cooldown + duration) - rain;\n displayTimeLeft = secsToTime(timeLeft);\n } else {\n thunderStormNow = false;\n long nextThunderstorm = 0;\n if (thunderstorm < cooldown) {\n nextThunderstorm = cooldown - thunderstorm;\n } else if ((cooldown + duration) <= thunderstorm) {\n nextThunderstorm = ((cooldown + duration) * thunderstormInterval) - thunderstorm + cooldown;\n }\n if(nextThunderstorm == cooldown - rain){\n netxIsStorm = true;\n displayNextRain = secsToTime(nextThunderstorm);\n } else {\n netxIsStorm = false;\n }\n }\n thunderStormNowCache = thunderStormNow;\n rainNowCache = rainNow;\n netxIsStormCache = netxIsStorm;\n }\n private static String secsToTime(long seconds) {\n return sdf.format(new Date(seconds * 1000)).substring(14, 19);\n }\n}" }, { "identifier": "LocationUtils", "path": "src/main/java/me/greencat/skyimprover/utils/LocationUtils.java", "snippet": "public class LocationUtils {\n public static boolean isOnSkyblock = false;\n public static boolean isInDungeons = false;\n public static boolean isInKuudra = false;\n public static final ObjectArrayList<String> STRING_SCOREBOARD = new ObjectArrayList<>();\n\n public static void update(){\n MinecraftClient minecraftClient = MinecraftClient.getInstance();\n updateScoreboard(minecraftClient);\n updatePlayerPresenceFromScoreboard(minecraftClient);\n }\n public static void updatePlayerPresenceFromScoreboard(MinecraftClient client) {\n List<String> sidebar = STRING_SCOREBOARD;\n\n FabricLoader fabricLoader = FabricLoader.getInstance();\n if (client.world == null || client.isInSingleplayer() || sidebar.isEmpty()) {\n isOnSkyblock = false;\n isInDungeons = false;\n isInKuudra = false;\n }\n\n if (sidebar.isEmpty() && !fabricLoader.isDevelopmentEnvironment()) return;\n String string = sidebar.toString();\n if(sidebar.isEmpty()){\n isInDungeons = false;\n isInKuudra = false;\n return;\n }\n if (sidebar.get(0).contains(\"SKYBLOCK\") || sidebar.get(0).contains(\"SKIBLOCK\")) {\n if (!isOnSkyblock) {\n isOnSkyblock = true;\n }\n } else {\n isOnSkyblock = false;\n }\n isInDungeons = isOnSkyblock && string.contains(\"The Catacombs\");\n isInKuudra = isOnSkyblock && string.contains(\"Kuudra\");\n }\n private static void updateScoreboard(MinecraftClient client) {\n try {\n STRING_SCOREBOARD.clear();\n\n ClientPlayerEntity player = client.player;\n if (player == null) return;\n\n Scoreboard scoreboard = player.getScoreboard();\n ScoreboardObjective objective = scoreboard.getObjectiveForSlot(1);\n ObjectArrayList<Text> textLines = new ObjectArrayList<>();\n ObjectArrayList<String> stringLines = new ObjectArrayList<>();\n\n for (ScoreboardPlayerScore score : scoreboard.getAllPlayerScores(objective)) {\n Team team = scoreboard.getPlayerTeam(score.getPlayerName());\n\n if (team != null) {\n Text textLine = Text.empty().append(team.getPrefix().copy()).append(team.getSuffix().copy());\n String strLine = team.getPrefix().getString() + team.getSuffix().getString();\n\n if (!strLine.trim().isEmpty()) {\n String formatted = Formatting.strip(strLine);\n\n textLines.add(textLine);\n stringLines.add(formatted);\n }\n }\n }\n\n if (objective != null) {\n stringLines.add(objective.getDisplayName().getString());\n textLines.add(Text.empty().append(objective.getDisplayName().copy()));\n\n Collections.reverse(stringLines);\n Collections.reverse(textLines);\n }\n STRING_SCOREBOARD.addAll(stringLines);\n } catch (NullPointerException ignored) {\n\n }\n }\n}" } ]
import eu.midnightdust.lib.config.MidnightConfig; import me.greencat.skyimprover.config.Config; import me.greencat.skyimprover.feature.FeatureLoader; import me.greencat.skyimprover.feature.damageSplash.DamageSplash; import me.greencat.skyimprover.feature.dungeonDeathMessage.DungeonDeathMessage; import me.greencat.skyimprover.feature.kuudraHelper.KuudraHelper; import me.greencat.skyimprover.feature.m3Freeze.M3FreezeHelper; import me.greencat.skyimprover.feature.rainTimer.RainTimer; import me.greencat.skyimprover.utils.LocationUtils; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
4,768
package me.greencat.skyimprover; public class SkyImprover implements ClientModInitializer { public static final String MODID = "skyimprover"; @Override public void onInitializeClient() { MidnightConfig.init(MODID, Config.class);
package me.greencat.skyimprover; public class SkyImprover implements ClientModInitializer { public static final String MODID = "skyimprover"; @Override public void onInitializeClient() { MidnightConfig.init(MODID, Config.class);
FeatureLoader.loadAll("me.greencat.skyimprover.feature");
1
2023-10-19 09:19:09+00:00
8k
histevehu/12306
business/src/main/java/com/steve/train/business/controller/admin/DailyTrainStationAdminController.java
[ { "identifier": "DailyTrainStationQueryReq", "path": "business/src/main/java/com/steve/train/business/req/DailyTrainStationQueryReq.java", "snippet": "public class DailyTrainStationQueryReq extends PageReq {\n\n /**\n * 日期\n */\n @DateTimeFormat(pattern = \"yyyy-MM-dd\")\n private Date date;\n\n /**\n * 车次编号\n */\n private String trainCode;\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public String getTrainCode() {\n return trainCode;\n }\n\n public void setTrainCode(String trainCode) {\n this.trainCode = trainCode;\n }\n\n @Override\n public String toString() {\n return \"DailyTrainStationQueryReq{\" +\n \"date=\" + date +\n \", trainCode='\" + trainCode + '\\'' +\n \"} \" + super.toString();\n }\n}" }, { "identifier": "DailyTrainStationSaveReq", "path": "business/src/main/java/com/steve/train/business/req/DailyTrainStationSaveReq.java", "snippet": "public class DailyTrainStationSaveReq {\n\n /**\n * id\n */\n private Long id;\n\n /**\n * 日期\n */\n @JsonFormat(pattern = \"yyyy-MM-dd\", timezone = \"GMT+8\")\n @NotNull(message = \"日期不能为空\")\n private Date date;\n\n /**\n * 车次编号\n */\n @NotBlank(message = \"车次编号不能为空\")\n private String trainCode;\n\n /**\n * 站序\n */\n @NotNull(message = \"站序不能为空\")\n private Integer index;\n\n /**\n * 站名\n */\n @NotBlank(message = \"站名不能为空\")\n private String name;\n\n /**\n * 站名拼音\n */\n @NotBlank(message = \"站名拼音不能为空\")\n private String namePinyin;\n\n /**\n * 进站时间\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date inTime;\n\n /**\n * 出站时间\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date outTime;\n\n /**\n * 停站时长\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date stopTime;\n\n /**\n * 里程(公里)|从上一站到本站的距离\n */\n @NotNull(message = \"里程(公里)不能为空\")\n private BigDecimal km;\n\n /**\n * 新增时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date createTime;\n\n /**\n * 修改时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date updateTime;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public String getTrainCode() {\n return trainCode;\n }\n\n public void setTrainCode(String trainCode) {\n this.trainCode = trainCode;\n }\n\n public Integer getIndex() {\n return index;\n }\n\n public void setIndex(Integer index) {\n this.index = index;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNamePinyin() {\n return namePinyin;\n }\n\n public void setNamePinyin(String namePinyin) {\n this.namePinyin = namePinyin;\n }\n\n public Date getInTime() {\n return inTime;\n }\n\n public void setInTime(Date inTime) {\n this.inTime = inTime;\n }\n\n public Date getOutTime() {\n return outTime;\n }\n\n public void setOutTime(Date outTime) {\n this.outTime = outTime;\n }\n\n public Date getStopTime() {\n return stopTime;\n }\n\n public void setStopTime(Date stopTime) {\n this.stopTime = stopTime;\n }\n\n public BigDecimal getKm() {\n return km;\n }\n\n public void setKm(BigDecimal km) {\n this.km = km;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", date=\").append(date);\n sb.append(\", trainCode=\").append(trainCode);\n sb.append(\", index=\").append(index);\n sb.append(\", name=\").append(name);\n sb.append(\", namePinyin=\").append(namePinyin);\n sb.append(\", inTime=\").append(inTime);\n sb.append(\", outTime=\").append(outTime);\n sb.append(\", stopTime=\").append(stopTime);\n sb.append(\", km=\").append(km);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", updateTime=\").append(updateTime);\n sb.append(\"]\");\n return sb.toString();\n }\n}" }, { "identifier": "DailyTrainStationQueryResp", "path": "business/src/main/java/com/steve/train/business/resp/DailyTrainStationQueryResp.java", "snippet": "public class DailyTrainStationQueryResp {\n\n /**\n * id\n */\n @JsonSerialize(using = ToStringSerializer.class)\n private Long id;\n\n /**\n * 日期\n */\n @JsonFormat(pattern = \"yyyy-MM-dd\", timezone = \"GMT+8\")\n private Date date;\n\n /**\n * 车次编号\n */\n private String trainCode;\n\n /**\n * 站序\n */\n private Integer index;\n\n /**\n * 站名\n */\n private String name;\n\n /**\n * 站名拼音\n */\n private String namePinyin;\n\n /**\n * 进站时间\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date inTime;\n\n /**\n * 出站时间\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date outTime;\n\n /**\n * 停站时长\n */\n @JsonFormat(pattern = \"HH:mm:ss\", timezone = \"GMT+8\")\n private Date stopTime;\n\n /**\n * 里程(公里)|从上一站到本站的距离\n */\n private BigDecimal km;\n\n /**\n * 新增时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date createTime;\n\n /**\n * 修改时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date updateTime;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public String getTrainCode() {\n return trainCode;\n }\n\n public void setTrainCode(String trainCode) {\n this.trainCode = trainCode;\n }\n\n public Integer getIndex() {\n return index;\n }\n\n public void setIndex(Integer index) {\n this.index = index;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNamePinyin() {\n return namePinyin;\n }\n\n public void setNamePinyin(String namePinyin) {\n this.namePinyin = namePinyin;\n }\n\n public Date getInTime() {\n return inTime;\n }\n\n public void setInTime(Date inTime) {\n this.inTime = inTime;\n }\n\n public Date getOutTime() {\n return outTime;\n }\n\n public void setOutTime(Date outTime) {\n this.outTime = outTime;\n }\n\n public Date getStopTime() {\n return stopTime;\n }\n\n public void setStopTime(Date stopTime) {\n this.stopTime = stopTime;\n }\n\n public BigDecimal getKm() {\n return km;\n }\n\n public void setKm(BigDecimal km) {\n this.km = km;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", date=\").append(date);\n sb.append(\", trainCode=\").append(trainCode);\n sb.append(\", index=\").append(index);\n sb.append(\", name=\").append(name);\n sb.append(\", namePinyin=\").append(namePinyin);\n sb.append(\", inTime=\").append(inTime);\n sb.append(\", outTime=\").append(outTime);\n sb.append(\", stopTime=\").append(stopTime);\n sb.append(\", km=\").append(km);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", updateTime=\").append(updateTime);\n sb.append(\"]\");\n return sb.toString();\n }\n}" }, { "identifier": "DailyTrainStationService", "path": "business/src/main/java/com/steve/train/business/service/DailyTrainStationService.java", "snippet": "@Service\npublic class DailyTrainStationService {\n\n private static final Logger LOG = LoggerFactory.getLogger(DailyTrainStationService.class);\n\n @Resource\n private DailyTrainStationMapper dailyTrainStationMapper;\n @Resource\n private TrainStationService trainStationService;\n\n public void save(DailyTrainStationSaveReq req) {\n DateTime now = DateTime.now();\n DailyTrainStation dailyTrainStation = BeanUtil.copyProperties(req, DailyTrainStation.class);\n if (ObjectUtil.isNull(dailyTrainStation.getId())) {\n dailyTrainStation.setId(SnowFlakeUtil.getSnowFlakeNextId());\n dailyTrainStation.setCreateTime(now);\n dailyTrainStation.setUpdateTime(now);\n dailyTrainStationMapper.insert(dailyTrainStation);\n } else {\n dailyTrainStation.setUpdateTime(now);\n dailyTrainStationMapper.updateByPrimaryKey(dailyTrainStation);\n }\n }\n\n public PageResp<DailyTrainStationQueryResp> queryList(DailyTrainStationQueryReq req) {\n DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();\n dailyTrainStationExample.setOrderByClause(\"date desc, train_code asc, `index` asc\");\n DailyTrainStationExample.Criteria criteria = dailyTrainStationExample.createCriteria();\n if (ObjUtil.isNotNull(req.getDate())) {\n criteria.andDateEqualTo(req.getDate());\n }\n if (ObjUtil.isNotEmpty(req.getTrainCode())) {\n criteria.andTrainCodeEqualTo(req.getTrainCode());\n }\n\n LOG.info(\"查询页码:{}\", req.getPage());\n LOG.info(\"每页条数:{}\", req.getSize());\n PageHelper.startPage(req.getPage(), req.getSize());\n List<DailyTrainStation> dailyTrainStationList = dailyTrainStationMapper.selectByExample(dailyTrainStationExample);\n\n PageInfo<DailyTrainStation> pageInfo = new PageInfo<>(dailyTrainStationList);\n LOG.info(\"总行数:{}\", pageInfo.getTotal());\n LOG.info(\"总页数:{}\", pageInfo.getPages());\n\n List<DailyTrainStationQueryResp> list = BeanUtil.copyToList(dailyTrainStationList, DailyTrainStationQueryResp.class);\n\n PageResp<DailyTrainStationQueryResp> pageResp = new PageResp<>();\n pageResp.setTotal(pageInfo.getTotal());\n pageResp.setList(list);\n return pageResp;\n }\n\n public void delete(Long id) {\n dailyTrainStationMapper.deleteByPrimaryKey(id);\n }\n\n @Transactional\n public void genDaily(Date date, String trainCode) {\n LOG.info(\"生成日期【{}】车次【{}】的车站信息开始\", DateUtil.formatDate(date), trainCode);\n\n // 删除某日某车次的车站信息\n DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();\n dailyTrainStationExample.createCriteria()\n .andDateEqualTo(date)\n .andTrainCodeEqualTo(trainCode);\n dailyTrainStationMapper.deleteByExample(dailyTrainStationExample);\n\n // 查出某车次的所有的车站信息\n List<TrainStation> stationList = trainStationService.selectByTrainCode(trainCode);\n if (CollUtil.isEmpty(stationList)) {\n LOG.info(\"该车次没有车站基础数据,生成该车次的车站信息结束\");\n return;\n }\n\n for (TrainStation trainStation : stationList) {\n DateTime now = DateTime.now();\n DailyTrainStation dailyTrainStation = BeanUtil.copyProperties(trainStation, DailyTrainStation.class);\n dailyTrainStation.setId(SnowFlakeUtil.getSnowFlakeNextId());\n dailyTrainStation.setCreateTime(now);\n dailyTrainStation.setUpdateTime(now);\n dailyTrainStation.setDate(date);\n dailyTrainStationMapper.insert(dailyTrainStation);\n }\n LOG.info(\"生成日期【{}】车次【{}】的车站信息结束\", DateUtil.formatDate(date), trainCode);\n }\n\n /**\n * 按车次查询全部车站\n */\n public long countByTrainCode(Date date, String trainCode) {\n DailyTrainStationExample example = new DailyTrainStationExample();\n example.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode);\n return dailyTrainStationMapper.countByExample(example);\n }\n\n public List<DailyTrainStationQueryResp> queryByTrain(Date date, String trainCode) {\n DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();\n dailyTrainStationExample.setOrderByClause(\"`index` asc\");\n dailyTrainStationExample.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode);\n List<DailyTrainStation> list = dailyTrainStationMapper.selectByExample(dailyTrainStationExample);\n return BeanUtil.copyToList(list, DailyTrainStationQueryResp.class);\n }\n}" }, { "identifier": "CommonResp", "path": "common/src/main/java/com/steve/train/common/resp/CommonResp.java", "snippet": "public class CommonResp<T> {\n\n /**\n * 业务上的成功或失败\n */\n private boolean success = true;\n\n /**\n * 返回信息\n */\n private String message;\n\n /**\n * 返回泛型数据,自定义类型\n */\n private T content;\n\n public CommonResp() {\n }\n\n public CommonResp(boolean success, String message, T content) {\n this.success = success;\n this.message = message;\n this.content = content;\n }\n\n public CommonResp(T content) {\n this.content = content;\n }\n\n public boolean getSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public T getContent() {\n return content;\n }\n\n public void setContent(T content) {\n this.content = content;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"CommonResp{\");\n sb.append(\"success=\").append(success);\n sb.append(\", message='\").append(message).append('\\'');\n sb.append(\", content=\").append(content);\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "PageResp", "path": "common/src/main/java/com/steve/train/common/resp/PageResp.java", "snippet": "public class PageResp<T> implements Serializable {\n\n // 总条数\n private Long total;\n\n // 当前页的列表\n private List<T> list;\n\n public Long getTotal() {\n return total;\n }\n\n public void setTotal(Long total) {\n this.total = total;\n }\n\n public List<T> getList() {\n return list;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n @Override\n public String toString() {\n return \"PageResp{\" +\n \"total=\" + total +\n \", list=\" + list +\n '}';\n }\n}" } ]
import com.steve.train.business.req.DailyTrainStationQueryReq; import com.steve.train.business.req.DailyTrainStationSaveReq; import com.steve.train.business.resp.DailyTrainStationQueryResp; import com.steve.train.business.service.DailyTrainStationService; import com.steve.train.common.resp.CommonResp; import com.steve.train.common.resp.PageResp; import jakarta.annotation.Resource; import jakarta.validation.Valid; import org.springframework.web.bind.annotation.*;
4,507
package com.steve.train.business.controller.admin; /* * @author : Steve Hu * @date : 2023-11-01 09:10:50 * @description: 每日车站管理员接口(FreeMarker生成) */ @RestController @RequestMapping("/admin/dailyTrainStation") public class DailyTrainStationAdminController { @Resource private DailyTrainStationService dailyTrainStationService; @PostMapping("/save")
package com.steve.train.business.controller.admin; /* * @author : Steve Hu * @date : 2023-11-01 09:10:50 * @description: 每日车站管理员接口(FreeMarker生成) */ @RestController @RequestMapping("/admin/dailyTrainStation") public class DailyTrainStationAdminController { @Resource private DailyTrainStationService dailyTrainStationService; @PostMapping("/save")
public CommonResp<Object> save(@Valid @RequestBody DailyTrainStationSaveReq req) {
4
2023-10-23 01:20:56+00:00
8k
team-moabam/moabam-BE
src/test/java/com/moabam/api/presentation/ReportControllerTest.java
[ { "identifier": "Member", "path": "src/main/java/com/moabam/api/domain/member/Member.java", "snippet": "@Entity\n@Getter\n@Table(name = \"member\")\n@SQLDelete(sql = \"UPDATE member SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Member extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"social_id\", nullable = false, unique = true)\n\tprivate String socialId;\n\n\t@Column(name = \"nickname\", unique = true)\n\tprivate String nickname;\n\n\t@Column(name = \"intro\", length = 30)\n\tprivate String intro;\n\n\t@Column(name = \"profile_image\", nullable = false)\n\tprivate String profileImage;\n\n\t@Column(name = \"morning_image\", nullable = false)\n\tprivate String morningImage;\n\n\t@Column(name = \"night_image\", nullable = false)\n\tprivate String nightImage;\n\n\t@Column(name = \"total_certify_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate long totalCertifyCount;\n\n\t@Column(name = \"report_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int reportCount;\n\n\t@Column(name = \"current_night_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int currentNightCount;\n\n\t@Column(name = \"current_morning_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int currentMorningCount;\n\n\t@Embedded\n\tprivate Bug bug;\n\n\t@Enumerated(EnumType.STRING)\n\t@Column(name = \"role\", nullable = false)\n\t@ColumnDefault(\"'USER'\")\n\tprivate Role role;\n\n\t@Column(name = \"deleted_at\")\n\tprivate LocalDateTime deletedAt;\n\n\t@Builder\n\tprivate Member(Long id, String socialId, Bug bug) {\n\t\tthis.id = id;\n\t\tthis.socialId = requireNonNull(socialId);\n\t\tthis.nickname = createNickName();\n\t\tthis.intro = \"\";\n\t\tthis.profileImage = IMAGE_DOMAIN + MEMBER_PROFILE_URL;\n\t\tthis.morningImage = IMAGE_DOMAIN + DEFAULT_MORNING_EGG_URL;\n\t\tthis.nightImage = IMAGE_DOMAIN + DEFAULT_NIGHT_EGG_URL;\n\t\tthis.bug = requireNonNull(bug);\n\t\tthis.role = Role.USER;\n\t}\n\n\tpublic void enterRoom(RoomType roomType) {\n\t\tif (roomType.equals(RoomType.MORNING)) {\n\t\t\tthis.currentMorningCount++;\n\t\t\treturn;\n\t\t}\n\n\t\tif (roomType.equals(RoomType.NIGHT)) {\n\t\t\tthis.currentNightCount++;\n\t\t}\n\t}\n\n\tpublic void exitRoom(RoomType roomType) {\n\t\tif (roomType.equals(RoomType.MORNING) && currentMorningCount > 0) {\n\t\t\tthis.currentMorningCount--;\n\t\t\treturn;\n\t\t}\n\n\t\tif (roomType.equals(RoomType.NIGHT) && currentNightCount > 0) {\n\t\t\tthis.currentNightCount--;\n\t\t}\n\t}\n\n\tpublic int getLevel() {\n\t\treturn (int)(totalCertifyCount / LEVEL_DIVISOR) + 1;\n\t}\n\n\tpublic void increaseTotalCertifyCount() {\n\t\tthis.totalCertifyCount++;\n\t}\n\n\tpublic void delete(LocalDateTime now) {\n\t\tsocialId = deleteSocialId(now);\n\t\tnickname = null;\n\t}\n\n\tpublic boolean changeNickName(String nickname) {\n\t\tif (Objects.isNull(nickname)) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.nickname = nickname;\n\t\treturn true;\n\t}\n\n\tpublic void changeIntro(String intro) {\n\t\tthis.intro = requireNonNullElse(intro, this.intro);\n\t}\n\n\tpublic void changeProfileUri(String newProfileUri) {\n\t\tthis.profileImage = requireNonNullElse(newProfileUri, profileImage);\n\t}\n\n\tpublic void changeDefaultSkintUrl(Item item) throws NotFoundException {\n\t\tif (ItemType.MORNING.equals(item.getType())) {\n\t\t\tthis.morningImage = item.getAwakeImage();\n\t\t\treturn;\n\t\t}\n\n\t\tif (ItemType.NIGHT.equals(item.getType())) {\n\t\t\tthis.nightImage = item.getAwakeImage();\n\t\t\treturn;\n\t\t}\n\n\t\tthrow new NotFoundException(SKIN_TYPE_NOT_FOUND);\n\t}\n\n\tprivate String createNickName() {\n\t\treturn \"오목눈이#\" + randomStringValues();\n\t}\n\n\tprivate String deleteSocialId(LocalDateTime now) {\n\t\treturn \"delete_\" + now.toString() + randomNumberValues();\n\t}\n}" }, { "identifier": "MemberRepository", "path": "src/main/java/com/moabam/api/domain/member/repository/MemberRepository.java", "snippet": "public interface MemberRepository extends JpaRepository<Member, Long> {\n\n\tOptional<Member> findBySocialId(String id);\n\n\tboolean existsByNickname(String nickname);\n}" }, { "identifier": "Certification", "path": "src/main/java/com/moabam/api/domain/room/Certification.java", "snippet": "@Entity\n@Getter\n@Table(name = \"certification\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Certification extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"routine_id\", nullable = false, updatable = false)\n\tprivate Routine routine;\n\n\t@Column(name = \"member_id\", nullable = false, updatable = false)\n\tprivate Long memberId;\n\n\t@Column(name = \"image\", nullable = false)\n\tprivate String image;\n\n\t@Builder\n\tprivate Certification(Long id, Routine routine, Long memberId, String image) {\n\t\tthis.id = id;\n\t\tthis.routine = requireNonNull(routine);\n\t\tthis.memberId = requireNonNull(memberId);\n\t\tthis.image = requireNonNull(image);\n\t}\n\n\tpublic void changeImage(String image) {\n\t\tthis.image = image;\n\t}\n}" }, { "identifier": "Room", "path": "src/main/java/com/moabam/api/domain/room/Room.java", "snippet": "@Entity\n@Getter\n@Table(name = \"room\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@SQLDelete(sql = \"UPDATE room SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\npublic class Room extends BaseTimeEntity {\n\n\tprivate static final int LEVEL_0 = 0;\n\tprivate static final int LEVEL_1 = 1;\n\tprivate static final int LEVEL_2 = 2;\n\tprivate static final int LEVEL_3 = 3;\n\tprivate static final int LEVEL_4 = 4;\n\tprivate static final int LEVEL_5 = 5;\n\tprivate static final String ROOM_LEVEL_0_IMAGE = \"https://image.moabam.com/moabam/default/room-level-00.png\";\n\tprivate static final String ROOM_LEVEL_1_IMAGE = \"https://image.moabam.com/moabam/default/room-level-01.png\";\n\tprivate static final String ROOM_LEVEL_2_IMAGE = \"https://image.moabam.com/moabam/default/room-level-02.png\";\n\tprivate static final String ROOM_LEVEL_3_IMAGE = \"https://image.moabam.com/moabam/default/room-level-03.png\";\n\tprivate static final String ROOM_LEVEL_4_IMAGE = \"https://image.moabam.com/moabam/default/room-level-04.png\";\n\tprivate static final String ROOM_LEVEL_5_IMAGE = \"https://image.moabam.com/moabam/default/room-level-05.png\";\n\tprivate static final int MORNING_START_TIME = 4;\n\tprivate static final int MORNING_END_TIME = 10;\n\tprivate static final int NIGHT_START_TIME = 20;\n\tprivate static final int NIGHT_END_TIME = 2;\n\tprivate static final int CLOCK_ZERO = 0;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"title\",\n\t\tcolumnDefinition = \"VARCHAR(20) NOT NULL, FULLTEXT INDEX full_title (title) WITH PARSER ngram\")\n\tprivate String title;\n\n\t@Column(name = \"password\", length = 8)\n\tprivate String password;\n\n\t@ColumnDefault(\"0\")\n\t@Column(name = \"level\", nullable = false)\n\tprivate int level;\n\n\t@ColumnDefault(\"0\")\n\t@Column(name = \"exp\", nullable = false)\n\tprivate int exp;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"room_type\")\n\tprivate RoomType roomType;\n\n\t@Column(name = \"certify_time\", nullable = false)\n\tprivate int certifyTime;\n\n\t@Column(name = \"current_user_count\", nullable = false)\n\tprivate int currentUserCount;\n\n\t@Column(name = \"max_user_count\", nullable = false)\n\tprivate int maxUserCount;\n\n\t@Column(name = \"announcement\", length = 100)\n\tprivate String announcement;\n\n\t@ColumnDefault(\"'\" + ROOM_LEVEL_0_IMAGE + \"'\")\n\t@Column(name = \"room_image\", length = 500)\n\tprivate String roomImage;\n\n\t@Column(name = \"manager_nickname\",\n\t\tcolumnDefinition = \"VARCHAR(30), FULLTEXT INDEX full_nickname (manager_nickname) WITH PARSER ngram\")\n\tprivate String managerNickname;\n\n\t@Column(name = \"deleted_at\")\n\tprivate LocalDateTime deletedAt;\n\n\t@Builder\n\tprivate Room(Long id, String title, String password, RoomType roomType, int certifyTime, int maxUserCount) {\n\t\tthis.id = id;\n\t\tthis.title = requireNonNull(title);\n\t\tthis.password = password;\n\t\tthis.level = 0;\n\t\tthis.exp = 0;\n\t\tthis.roomType = requireNonNull(roomType);\n\t\tthis.certifyTime = validateCertifyTime(roomType, certifyTime);\n\t\tthis.currentUserCount = 1;\n\t\tthis.maxUserCount = maxUserCount;\n\t\tthis.roomImage = ROOM_LEVEL_0_IMAGE;\n\t}\n\n\tpublic void levelUp() {\n\t\tthis.level += 1;\n\t\tthis.exp = 0;\n\t\tupgradeRoomImage(this.level);\n\t}\n\n\tpublic void upgradeRoomImage(int level) {\n\t\tif (level == LEVEL_1) {\n\t\t\tthis.roomImage = ROOM_LEVEL_1_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_2) {\n\t\t\tthis.roomImage = ROOM_LEVEL_2_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_3) {\n\t\t\tthis.roomImage = ROOM_LEVEL_3_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_4) {\n\t\t\tthis.roomImage = ROOM_LEVEL_4_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_5) {\n\t\t\tthis.roomImage = ROOM_LEVEL_5_IMAGE;\n\t\t}\n\t}\n\n\tpublic void gainExp() {\n\t\tthis.exp += 1;\n\t}\n\n\tpublic void changeAnnouncement(String announcement) {\n\t\tthis.announcement = announcement;\n\t}\n\n\tpublic void changeTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic void changePassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic void changeManagerNickname(String managerNickname) {\n\t\tthis.managerNickname = managerNickname;\n\t}\n\n\tpublic void changeMaxCount(int maxUserCount) {\n\t\tif (maxUserCount < this.currentUserCount) {\n\t\t\tthrow new BadRequestException(ROOM_MAX_USER_COUNT_MODIFY_FAIL);\n\t\t}\n\n\t\tthis.maxUserCount = maxUserCount;\n\t}\n\n\tpublic void increaseCurrentUserCount() {\n\t\tthis.currentUserCount += 1;\n\t}\n\n\tpublic void decreaseCurrentUserCount() {\n\t\tthis.currentUserCount -= 1;\n\t}\n\n\tpublic void changeCertifyTime(int certifyTime) {\n\t\tthis.certifyTime = validateCertifyTime(this.roomType, certifyTime);\n\t}\n\n\tprivate int validateCertifyTime(RoomType roomType, int certifyTime) {\n\t\tif (roomType.equals(MORNING) && (certifyTime < MORNING_START_TIME || certifyTime > MORNING_END_TIME)) {\n\t\t\tthrow new BadRequestException(INVALID_REQUEST_FIELD);\n\t\t}\n\n\t\tif (roomType.equals(NIGHT)\n\t\t\t&& ((certifyTime < NIGHT_START_TIME && certifyTime > NIGHT_END_TIME) || certifyTime < CLOCK_ZERO)) {\n\t\t\tthrow new BadRequestException(INVALID_REQUEST_FIELD);\n\t\t}\n\n\t\treturn certifyTime;\n\t}\n}" }, { "identifier": "Routine", "path": "src/main/java/com/moabam/api/domain/room/Routine.java", "snippet": "@Entity\n@Getter\n@Table(name = \"routine\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Routine extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"room_id\", updatable = false)\n\tprivate Room room;\n\n\t@Column(name = \"content\",\n\t\tcolumnDefinition = \"VARCHAR(20) NOT NULL, FULLTEXT INDEX full_content (content) WITH PARSER ngram\")\n\tprivate String content;\n\n\t@Builder\n\tprivate Routine(Long id, Room room, String content) {\n\t\tthis.id = id;\n\t\tthis.room = requireNonNull(room);\n\t\tthis.content = validateContent(content);\n\t}\n\n\tpublic void changeContent(String content) {\n\t\tthis.content = content;\n\t}\n\n\tprivate String validateContent(String content) {\n\t\tif (StringUtils.isBlank(content) || content.length() > 20) {\n\t\t\tthrow new BadRequestException(ROUTINE_LENGTH_ERROR);\n\t\t}\n\n\t\treturn content;\n\t}\n}" }, { "identifier": "CertificationRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/CertificationRepository.java", "snippet": "public interface CertificationRepository extends JpaRepository<Certification, Long> {\n\n}" }, { "identifier": "RoomRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/RoomRepository.java", "snippet": "public interface RoomRepository extends JpaRepository<Room, Long> {\n\n\t@Lock(LockModeType.PESSIMISTIC_WRITE)\n\tOptional<Room> findWithPessimisticLockByIdAndDeletedAtIsNull(Long id);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeyword(@Param(value = \"keyword\") String keyword);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.room_type = :roomType \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomType(@Param(value = \"keyword\") String keyword,\n\t\t@Param(value = \"roomType\") String roomType);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.id < :roomId \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomId(@Param(value = \"keyword\") String keyword, @Param(value = \"roomId\") Long roomId);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.room_type = :roomType \"\n\t\t+ \"and rm.id < :roomId \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomIdAndRoomType(@Param(value = \"keyword\") String keyword,\n\t\t@Param(value = \"roomType\") String roomType, @Param(value = \"roomId\") Long roomId);\n}" }, { "identifier": "RoutineRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/RoutineRepository.java", "snippet": "public interface RoutineRepository extends JpaRepository<Routine, Long> {\n\n\tList<Routine> findAllByRoomId(Long roomId);\n\n\tList<Routine> findAllByRoomIdIn(List<Long> roomIds);\n}" }, { "identifier": "WithoutFilterSupporter", "path": "src/test/java/com/moabam/support/common/WithoutFilterSupporter.java", "snippet": "@Import(DataCleanResolver.class)\n@ExtendWith({FilterProcessExtension.class, ClearDataExtension.class})\npublic class WithoutFilterSupporter {\n\n\t@MockBean\n\tprivate PathResolver pathResolver;\n\n\t@MockBean\n\tprivate DefaultHandlerExceptionResolver handlerExceptionResolver;\n\n\t@SpyBean\n\tprivate CorsFilter corsFilter;\n\n\t@MockBean\n\tprivate AllowOriginConfig allowOriginConfig;\n\n\t@BeforeEach\n\tvoid setUpMock() {\n\t\twillReturn(\"http://localhost:8080\")\n\t\t\t.given(corsFilter).getReferer(any());\n\n\t\twillReturn(Optional.of(PathResolver.Path.builder()\n\t\t\t.uri(\"/\")\n\t\t\t.role(Role.USER)\n\t\t\t.build()))\n\t\t\t.given(pathResolver).permitPathMatch(any());\n\t}\n}" }, { "identifier": "MemberFixture", "path": "src/test/java/com/moabam/support/fixture/MemberFixture.java", "snippet": "public final class MemberFixture {\n\n\tpublic static final String SOCIAL_ID = \"1\";\n\tpublic static final String NICKNAME = \"모아밤\";\n\n\tpublic static Member member() {\n\t\treturn Member.builder()\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(Long id) {\n\t\treturn Member.builder()\n\t\t\t.id(id)\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(Bug bug) {\n\t\treturn Member.builder()\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(bug)\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(String socialId) {\n\t\treturn Member.builder()\n\t\t\t.socialId(socialId)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n}" }, { "identifier": "ReportFixture", "path": "src/test/java/com/moabam/support/fixture/ReportFixture.java", "snippet": "public class ReportFixture {\n\n\tprivate static Long reportedId = 99L;\n\tprivate static Long roomId = 1L;\n\tprivate static Long certificationId = 1L;\n\n\tpublic static Report report(Room room, Certification certification) {\n\t\treturn Report.builder()\n\t\t\t.reporterId(1L)\n\t\t\t.reportedMemberId(2L)\n\t\t\t.room(room)\n\t\t\t.certification(certification)\n\t\t\t.build();\n\t}\n\n\tpublic static ReportRequest reportRequest() {\n\t\treturn new ReportRequest(reportedId, roomId, certificationId, \"description\");\n\t}\n\n\tpublic static ReportRequest reportRequest(Long reportedId, Long roomId, Long certificationId) {\n\t\treturn new ReportRequest(reportedId, roomId, certificationId, \"description\");\n\t}\n}" }, { "identifier": "RoomFixture", "path": "src/test/java/com/moabam/support/fixture/RoomFixture.java", "snippet": "public class RoomFixture {\n\n\tpublic static Room room() {\n\t\treturn Room.builder()\n\t\t\t.title(\"testTitle\")\n\t\t\t.roomType(RoomType.MORNING)\n\t\t\t.certifyTime(10)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(int certifyTime) {\n\t\treturn Room.builder()\n\t\t\t.id(1L)\n\t\t\t.title(\"testTitle\")\n\t\t\t.roomType(RoomType.MORNING)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(String title, RoomType roomType, int certifyTime) {\n\t\treturn Room.builder()\n\t\t\t.title(title)\n\t\t\t.roomType(roomType)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(String title, RoomType roomType, int certifyTime, String password) {\n\t\treturn Room.builder()\n\t\t\t.title(title)\n\t\t\t.password(password)\n\t\t\t.roomType(roomType)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Participant participant(Room room, Long memberId) {\n\t\treturn Participant.builder()\n\t\t\t.room(room)\n\t\t\t.memberId(memberId)\n\t\t\t.build();\n\t}\n\n\tpublic static Routine routine(Room room, String content) {\n\t\treturn Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(content)\n\t\t\t.build();\n\t}\n\n\tpublic static List<Routine> routines(Room room) {\n\t\tList<Routine> routines = new ArrayList<>();\n\n\t\tRoutine routine1 = Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(\"첫 루틴\")\n\t\t\t.build();\n\t\tRoutine routine2 = Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(\"두번째 루틴\")\n\t\t\t.build();\n\n\t\troutines.add(routine1);\n\t\troutines.add(routine2);\n\n\t\treturn routines;\n\t}\n\n\tpublic static Certification certification(Routine routine) {\n\t\treturn Certification.builder()\n\t\t\t.routine(routine)\n\t\t\t.memberId(1L)\n\t\t\t.image(\"test1\")\n\t\t\t.build();\n\t}\n\n\tpublic static DailyMemberCertification dailyMemberCertification(Long memberId, Long roomId,\n\t\tParticipant participant) {\n\t\treturn DailyMemberCertification.builder()\n\t\t\t.memberId(memberId)\n\t\t\t.roomId(roomId)\n\t\t\t.participant(participant)\n\t\t\t.build();\n\t}\n\n\tpublic static List<DailyMemberCertification> dailyMemberCertifications(Long roomId, Participant participant) {\n\n\t\tList<DailyMemberCertification> dailyMemberCertifications = new ArrayList<>();\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(1L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(2L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(3L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\n\t\treturn dailyMemberCertifications;\n\t}\n\n\tpublic static DailyRoomCertification dailyRoomCertification(Long roomId, LocalDate today) {\n\t\treturn DailyRoomCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.certifiedAt(today)\n\t\t\t.build();\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile1() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"1\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile2() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"2\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile3() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"3\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n}" } ]
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.time.LocalDateTime; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.member.repository.MemberRepository; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.report.ReportRequest; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.WithoutFilterSupporter; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.ReportFixture; import com.moabam.support.fixture.RoomFixture; import jakarta.persistence.EntityManagerFactory;
6,350
package com.moabam.api.presentation; @Transactional @SpringBootTest @AutoConfigureMockMvc @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ReportControllerTest extends WithoutFilterSupporter { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Autowired MemberRepository memberRepository; @Autowired RoomRepository roomRepository; @Autowired CertificationRepository certificationRepository; @Autowired RoutineRepository routineRepository; @Autowired EntityManagerFactory entityManagerFactory;
package com.moabam.api.presentation; @Transactional @SpringBootTest @AutoConfigureMockMvc @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ReportControllerTest extends WithoutFilterSupporter { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Autowired MemberRepository memberRepository; @Autowired RoomRepository roomRepository; @Autowired CertificationRepository certificationRepository; @Autowired RoutineRepository routineRepository; @Autowired EntityManagerFactory entityManagerFactory;
Member reportedMember;
0
2023-10-20 06:15:43+00:00
8k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/protocol/TestEncode.java
[ { "identifier": "TimeLocationData", "path": "src/main/java/Priloc/data/TimeLocationData.java", "snippet": "public class TimeLocationData implements Serializable {\n private Location loc;\n private Date date;\n private double accuracy = Constant.RADIUS;\n private TimeLocationData nTLD = null;\n private TimeLocationData pTLD = null;\n\n public TimeLocationData(Location loc, Date date) {\n this.loc = loc;\n this.date = date;\n }\n\n public TimeLocationData(Location loc, Date date, TimeLocationData nTLD) {\n this.loc = loc;\n this.date = date;\n this.nTLD = nTLD;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public void setNext(TimeLocationData nTLD) {\n this.nTLD = nTLD;\n }\n\n public void setPrevious(TimeLocationData pTLD) {\n this.pTLD = pTLD;\n }\n\n @Override\n public String toString() {\n return \"TrajectoryData{\" +\n \"loc=\" + loc +\n \", date=\" + date +\n '}';\n }\n\n public Location getLoc() {\n return loc;\n }\n\n public Date getDate() {\n return date;\n }\n\n public double getAccuracy() {\n return accuracy;\n }\n\n public boolean hasNext() {\n return nTLD != null;\n }\n\n public TimeLocationData next() {\n return nTLD;\n }\n\n public boolean hasPrevious() {\n return pTLD != null;\n }\n\n public TimeLocationData previous() {\n return pTLD;\n }\n\n public EncTmLocData encrypt(){\n return new EncTmLocData(this);\n }\n\n public Circle getCircle() {\n return new Circle(new Point(loc), accuracy);\n }\n}" }, { "identifier": "Trajectory", "path": "src/main/java/Priloc/data/Trajectory.java", "snippet": "public class Trajectory implements Callable<EncTrajectory>, Serializable {\n private List<TimeLocationData> TLDs;\n private String name;\n\n public Trajectory(List<TimeLocationData> tlds, String name) {\n this.TLDs = tlds;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n return \"Trajectory{\" +\n \"name='\" + name + '\\'' +\n \"size='\" + TLDs.size() + '\\'' +\n '}';\n }\n\n public List<TimeLocationData> getTLDs() {\n return TLDs;\n }\n\n public Date getStartDate() {\n return this.TLDs.get(0).getDate();\n }\n\n public Date getEndDate() {\n return this.TLDs.get(TLDs.size() - 1).getDate();\n }\n\n public EncTrajectory encrypt() {\n return new EncTrajectory(this);\n }\n\n public static boolean isIntersect(Trajectory t1, Trajectory t2) {\n // 判断时间重合\n Map<Date, List<Circle>> positiveCircles = new HashMap<>();\n for (TimeLocationData tld : t1.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n circles = new ArrayList<>();\n }\n circles.add(tld.getCircle());\n positiveCircles.put(startDate, circles);\n }\n for (TimeLocationData tld : t2.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n continue;\n }\n if (tld.getCircle().isIntersect(circles)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public EncTrajectory call() {\n return encrypt();\n }\n\n// /**\n// * 自定义序列化 搭配transist使用\n// */\n// private void writeObject(ObjectOutputStream out) throws IOException {\n// //只序列化以下3个成员变量\n// out.writeObject(this.TLDs);\n// out.writeObject(this.name);\n// }\n//\n// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n// //注意:read()的顺序要和write()的顺序一致。\n// this.TLDs = (List<TimeLocationData>) in.readObject();\n// this.name = (String) in.readObject();\n// TimeLocationData prev = null;\n// for (TimeLocationData curr : TLDs) {\n// curr.setPrevious(prev);\n// if (prev != null) {\n// prev.setNext(curr);\n// }\n// prev = curr;\n// }\n// }\n}" }, { "identifier": "TrajectoryReader", "path": "src/main/java/Priloc/data/TrajectoryReader.java", "snippet": "public class TrajectoryReader {\n private String path;\n private File pltFile;\n private Scanner scn;\n\n public TrajectoryReader(String path) throws FileNotFoundException {\n this.path = path;\n pltFile = new File(path);\n scn = new Scanner(pltFile);\n for (int i = 0; i < 6; i++) {\n scn.nextLine();\n }\n }\n\n public TrajectoryReader(File file) throws FileNotFoundException {\n pltFile = file;\n scn = new Scanner(pltFile);\n for (int i = 0; i < 6; i++) {\n scn.nextLine();\n }\n }\n\n public File getPltFile() {\n return pltFile;\n }\n\n private boolean hasNext() {\n return scn.hasNext();\n }\n\n private TimeLocationData next() throws ParseException {\n String[] tokens = scn.next().split(\",\");\n double lat = Double.parseDouble(tokens[0]);\n double lon = Double.parseDouble(tokens[1]);\n // 未引入高度\n double altitude = Double.parseDouble(tokens[3]); // Altitude in feet\n String time = tokens[5] + ' ' + tokens[6];\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n Date date = dateFormat.parse(time);\n if (Constant.IGNORE_DATE) {\n date.setYear(2008);\n date.setMonth(Calendar.JUNE);\n date.setDate(24);\n }\n return new TimeLocationData(new Location(lat, lon), date);\n }\n\n public Trajectory load() throws ParseException {\n List<TimeLocationData> tlds = new ArrayList<>();\n TimeLocationData pTLD = null;\n Date previousDate = null;\n double rad = 0;\n while (this.hasNext()) {\n TimeLocationData cTLD = this.next();\n Date currentDate = Utils.getStart(cTLD.getDate());\n if (currentDate.equals(previousDate)) {\n // distance\n rad = Math.max(rad, cTLD.getLoc().distance(pTLD.getLoc()));\n if (rad < Constant.RADIUS * 1.5) {\n continue;\n }\n }\n if (rad > Constant.RADIUS * 2) {\n // TODO 补充rad/2r个园\n TimeLocationData mTLD = new TimeLocationData(new Location(\n (cTLD.getLoc().getLatitude() + pTLD.getLoc().getLatitude()) / 2.0,\n (cTLD.getLoc().getLongitude() + pTLD.getLoc().getLongitude()) / 2.0\n ), currentDate);\n // 连接双向链表\n mTLD.setPrevious(pTLD);\n mTLD.setNext(cTLD);\n // 将节点加入到轨迹中\n tlds.add(mTLD);\n // 设置当前节点为Previous\n pTLD = mTLD;\n }\n rad = 0;\n // 设置时间为标准间隔\n cTLD.setDate(currentDate);\n // 连接双向链表\n cTLD.setPrevious(pTLD);\n if (pTLD != null) {\n pTLD.setNext(cTLD);\n }\n // 将节点加入到轨迹中\n tlds.add(cTLD);\n // 设置当前节点为Previous\n pTLD = cTLD;\n previousDate = currentDate;\n }\n return new Trajectory(tlds, pltFile.getName());\n }\n\n public static boolean check(Trajectory t) {\n Circle pc = null;\n for (TimeLocationData tld : t.getTLDs()) {\n Circle cc = tld.getCircle();\n if (pc != null) {\n if (Point.distance(cc.getCenter(), pc.getCenter()) > Constant.RADIUS * 3) {\n // System.out.println(Point.distance(cc.getCenter(), pc.getCenter()) + \"\" + tld.getDate());\n return false;\n }\n }\n pc = cc;\n }\n return true;\n }\n\n public static void main(String[] args) {\n try {\n TrajectoryReader pltReader = new TrajectoryReader(\"./GeoLife Trajectories 1.3/data by person/000/Trajectory/20081023025304.plt\");\n while (pltReader.hasNext()) {\n System.out.println(pltReader.next());\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}" }, { "identifier": "Location", "path": "src/main/java/Priloc/geo/Location.java", "snippet": "public class Location implements Serializable {\n private double latitude;\n private double longitude;\n private double altitude = 0.0;\n\n public Location(double latitude, double longitude, double altitude) {\n this(latitude, longitude);\n this.altitude = altitude;\n }\n\n public Location(double latitude, double longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n @Override\n public String toString() {\n return \"PlainLocation{\" +\n \"latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", altitude=\" + altitude +\n //\", XYZ=\" + toXYZ() +\n '}';\n }\n\n public Turple<Double, Double, Double> toXYZ() {\n return Utils.gcj02ToXYZ(longitude, latitude, altitude);\n }\n\n public EncryptedPoint encrypt() {\n Turple<Double, Double, Double> xyz = toXYZ();\n return new EncryptedPoint(xyz.first, xyz.second, xyz.third);\n }\n\n public double squareDistance(Location other) {\n// Turple<Double, Double, Double> xyz1 = toXYZ();\n// Turple<Double, Double, Double> xyz2 = other.toXYZ();\n// return Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.pow(distance(other), 2);\n }\n\n public double distance(Location other) {\n// return Math.sqrt(squareDistance(other));\n GlobalCoordinates source = new GlobalCoordinates(latitude, longitude);\n GlobalCoordinates target = new GlobalCoordinates(other.latitude, other.longitude);\n return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, source, target).getEllipsoidalDistance();\n }\n\n public double encodeDistance(Location other) {\n Turple<Double, Double, Double> xyz1 = toXYZ();\n Turple<Double, Double, Double> xyz2 = other.toXYZ();\n double squareDist = Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.sqrt(squareDist);\n }\n}" }, { "identifier": "Constant", "path": "src/main/java/Priloc/utils/Constant.java", "snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{2160000, 1820000, -5690000};\n\n public static final boolean IGNORE_DATE = true;\n public static final boolean REJECT_R_LESS_P5 = true;\n\n // 时间段大小\n public final static int INTERVAL = 10;\n // 每个时间段的移动最大距离\n public static final double RADIUS = 200.0;\n // TODO 优化 不同时间段的活跃距离\n public static final double[] COMPARE_DISTANCE = new double[]{1200 * 1200.0};\n public static final int[] PRUNE_NUM = new int[]{0, 2};\n // 控制形状拟合效果\n public static final int TRIANGLE_NUM = 100;\n public static final Circle.circleFilter FILTER = new Circle.distantFilter(); //new Circle.areaFilter();\n\n public static String toStr() {\n return \"Constant{\" +\n \"INTERVAL=\" + INTERVAL +\n \", RADIUS=\" + RADIUS +\n \", IGNORE_DATE=\" + IGNORE_DATE +\n \", REJECT_R_LESS_P5=\" + REJECT_R_LESS_P5 +\n \", COMPARE_DISTANCE=\" + Arrays.toString(COMPARE_DISTANCE) +\n \", PRUNE_NUM=\" + Arrays.toString(PRUNE_NUM) +\n \", TRIANGLE_NUM=\" + TRIANGLE_NUM +\n \", FILTER=\" + FILTER +\n '}';\n }\n}" } ]
import Priloc.data.TimeLocationData; import Priloc.data.Trajectory; import Priloc.data.TrajectoryReader; import Priloc.geo.Location; import Priloc.utils.Constant; import java.util.List; import static java.lang.System.exit;
4,049
package Priloc.protocol; public class TestEncode { // public static void main(String[] args) throws Exception { // String[] negativePath = new String[]{ // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt", // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt" // }; // TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeReaders[i] = new TrajectoryReader(negativePath[i]); // } // Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeTrajectories[i] = negativeReaders[i].load(); // } // double maxError = 0; // for (int i = 0; i < negativeTrajectories.length; i++) { // List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); // for(int j = 0; j < tlds.size() - 1; j++) { // Location l1 = tlds.get(j).getLoc(); // Location l2 = tlds.get(j + 1).getLoc(); // double expect = l1.distance(l2); // if (expect > 2 * Constant.RADIUS) { // continue; // } // double actual = l1.encodeDistance(l2); // //System.out.println(Math.abs(expect - actual)); // if (Math.abs(expect - actual) > maxError) { // maxError = Math.abs(expect - actual); // System.out.println(maxError); // } //// if (Math.abs(expect - actual) > 1) { //// System.out.println(l1); //// System.out.println(l2); //// System.out.println(expect); //// System.out.println(actual); //// } // } // } // } public static void main(String[] args) throws Exception { String[] negativePath = new String[]{ "./C++/dataset", }; TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeReaders[i] = new TrajectoryReader(negativePath[i]); } Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeTrajectories[i] = negativeReaders[i].load(); } double maxError = 0; for (int i = 0; i < negativeTrajectories.length; i++) { List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); for(int j = 0; j < tlds.size() - 1; j++) { Location l1 = tlds.get(j).getLoc(); Location l2 = tlds.get(j + 1).getLoc(); double expect = l1.distance(l2);
package Priloc.protocol; public class TestEncode { // public static void main(String[] args) throws Exception { // String[] negativePath = new String[]{ // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt", // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt" // }; // TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeReaders[i] = new TrajectoryReader(negativePath[i]); // } // Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeTrajectories[i] = negativeReaders[i].load(); // } // double maxError = 0; // for (int i = 0; i < negativeTrajectories.length; i++) { // List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); // for(int j = 0; j < tlds.size() - 1; j++) { // Location l1 = tlds.get(j).getLoc(); // Location l2 = tlds.get(j + 1).getLoc(); // double expect = l1.distance(l2); // if (expect > 2 * Constant.RADIUS) { // continue; // } // double actual = l1.encodeDistance(l2); // //System.out.println(Math.abs(expect - actual)); // if (Math.abs(expect - actual) > maxError) { // maxError = Math.abs(expect - actual); // System.out.println(maxError); // } //// if (Math.abs(expect - actual) > 1) { //// System.out.println(l1); //// System.out.println(l2); //// System.out.println(expect); //// System.out.println(actual); //// } // } // } // } public static void main(String[] args) throws Exception { String[] negativePath = new String[]{ "./C++/dataset", }; TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeReaders[i] = new TrajectoryReader(negativePath[i]); } Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeTrajectories[i] = negativeReaders[i].load(); } double maxError = 0; for (int i = 0; i < negativeTrajectories.length; i++) { List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); for(int j = 0; j < tlds.size() - 1; j++) { Location l1 = tlds.get(j).getLoc(); Location l2 = tlds.get(j + 1).getLoc(); double expect = l1.distance(l2);
if (expect > 2 * Constant.RADIUS) {
4
2023-10-22 06:28:51+00:00
8k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/listview/XmListViewSkin.java
[ { "identifier": "HueType", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/HueType.java", "snippet": "public enum HueType {\n /**\n * 暗色调, 在背景色是暗色的情况下,组件应该有的表现\n */\n DARK,\n /**\n * 亮色调, 在北京是亮色的情况下,组件应该有的表现\n */\n LIGHT,\n\n /**\n * 无色,就是没有背景色,没有边框色,只有文本或者图标颜色\n */\n NONE\n}" }, { "identifier": "SizeType", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/SizeType.java", "snippet": "public enum SizeType {\n\n /**\n * 小尺寸\n */\n SMALL,\n /**\n * 中等尺寸\n */\n MEDIUM,\n /**\n * 大尺寸\n */\n LARGE;\n}" }, { "identifier": "VirtualFlowScrollHelper", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/VirtualFlowScrollHelper.java", "snippet": "public class VirtualFlowScrollHelper {\n\n private static String H_INCREMENT_PATH = \"M10,0L10,6L15,3Z\",\n H_DECREMENT_PATH = \"M0,3L5,6L5,0Z\",\n V_INCREMENT_PATH = \"M0,0L10,0L5,3Z\",\n V_DECREMENT_PATH = \"M0,3L10,3L5,0Z\";\n\n private ScrollBar vbar, hbar;\n private Region vbarBackground, hbarBackground, vbarTrack, hbarTrack;\n private Region vbarIncrementBtn, vbarIncrementArrow, hbarIncrementBtn, hbarIncrementArrow,\n vbarDecrementBtn, vbarDecrementArrow, hbarDecrementBtn, hbarDecrementArrow;\n private StackPane vbarThumb, hbarThumb;\n\n private ObjectProperty<ColorType> colorType = new SimpleObjectProperty<ColorType>(ColorType.primary());\n public ColorType getColorType() {\n return colorType.get();\n }\n public ObjectProperty<ColorType> colorTypeProperty() {\n return colorType;\n }\n public void setColorType(ColorType colorType) {\n this.colorType.set(colorType);\n }\n\n public VirtualFlowScrollHelper(VirtualFlow flow){\n getBar(flow);\n updateSkin();\n\n colorType.addListener(propertyChangeListener);\n\n }\n\n private ChangeListener<Object> propertyChangeListener = (ob, ov, nv) ->{\n updateSkin();\n };\n\n /**\n * 获取虚拟滚动条,\n */\n private void getBar(VirtualFlow flow){\n ObservableList<Node> flowChildren = flow.getChildrenUnmodifiable();\n for (Node flowChild : flowChildren) {\n if(flowChild instanceof ScrollBar){\n ScrollBar bar = (ScrollBar) flowChild;\n Orientation orientation = bar.getOrientation();\n if(Orientation.VERTICAL.equals(orientation)){\n vbar = bar;\n }else if(Orientation.HORIZONTAL.equals(orientation)){\n hbar = bar;\n }\n }\n }\n getBarChildren();\n }\n\n /**\n * 获取滚动条的字子节点\n */\n private void getBarChildren(){\n hbar.setStyle(\"-fx-background-color: transparent;\");\n vbar.setStyle(\"-fx-background-color: transparent;\");\n ObservableList<Node> vbarChildren = vbar.getChildrenUnmodifiable();\n for (Node vbarChild : vbarChildren) {\n ObservableList<String> styleClass = vbarChild.getStyleClass();\n if(styleClass.contains(\"track-background\")){\n vbarBackground = (Region) vbarChild;\n }else if(styleClass.contains(\"increment-button\")){\n vbarIncrementBtn = (Region) vbarChild;\n vbarIncrementArrow = (Region) vbarIncrementBtn.getChildrenUnmodifiable().get(0);\n SVGPath incPath = new SVGPath();\n incPath.setContent(V_INCREMENT_PATH);\n vbarIncrementArrow.setShape(incPath);\n vbarIncrementBtn.setStyle(\"-fx-background-color: transparent;\");\n\n }else if(styleClass.contains(\"decrement-button\")){\n vbarDecrementBtn = (Region) vbarChild;\n vbarDecrementArrow = (Region) vbarDecrementBtn.getChildrenUnmodifiable().get(0);\n SVGPath decPath = new SVGPath();\n decPath.setContent(V_DECREMENT_PATH);\n vbarDecrementArrow.setShape(decPath);\n vbarDecrementBtn.setStyle(\"-fx-background-color: transparent;\");\n\n }else if(styleClass.contains(\"track\")){\n vbarTrack = (Region) vbarChild;\n vbarChild.setStyle(\"-fx-background-color: transparent;\");\n }else if(styleClass.contains(\"thumb\")){\n vbarThumb = (StackPane) vbarChild;\n }\n }\n\n ObservableList<Node> hbarChildren = hbar.getChildrenUnmodifiable();\n for (Node hbarChild : hbarChildren) {\n ObservableList<String> styleClass = hbarChild.getStyleClass();\n if(styleClass.contains(\"track-background\")){\n hbarBackground = (Region) hbarChild;\n }else if(styleClass.contains(\"increment-button\")){\n hbarIncrementBtn = (Region) hbarChild;\n hbarIncrementArrow = (Region) hbarIncrementBtn.getChildrenUnmodifiable().get(0);\n SVGPath incPath = new SVGPath();\n incPath.setContent(H_INCREMENT_PATH);\n hbarIncrementArrow.setShape(incPath);\n hbarIncrementBtn.setStyle(\"-fx-background-color: transparent;\");\n\n }else if(styleClass.contains(\"decrement-button\")){\n hbarDecrementBtn = (Region) hbarChild;\n hbarDecrementArrow = (Region) hbarDecrementBtn.getChildrenUnmodifiable().get(0);\n SVGPath decPath = new SVGPath();\n decPath.setContent(H_DECREMENT_PATH);\n hbarDecrementArrow.setShape(decPath);\n hbarDecrementBtn.setStyle(\"-fx-background-color: transparent;\");\n\n }else if(styleClass.contains(\"track\")){\n hbarTrack = (Region) hbarChild;\n hbarChild.setStyle(\"-fx-background-color: transparent;\");\n }else if(styleClass.contains(\"thumb\")){\n hbarThumb = (StackPane) hbarChild;\n }\n }\n }\n\n private ArrowBtnHoverListener hbarIncrementBtnHoverListener;\n private ArrowBtnHoverListener hbarDecrementBtnHoverListener;\n private ArrowBtnHoverListener vbarIncrementBtnHoverListener;\n private ArrowBtnHoverListener vbarDecrementBtnHoverListener;\n private ThumbHoverListener hbarThumbHoverListener;\n private ThumbHoverListener vbarThumbHoverListener;\n\n private void updateSkin() {\n\n if(hbarIncrementBtnHoverListener!=null && hbarIncrementBtn!=null){\n hbarIncrementBtn.hoverProperty().removeListener(hbarIncrementBtnHoverListener);\n }\n\n if(hbarDecrementBtnHoverListener!=null && hbarDecrementBtn!=null){\n hbarDecrementBtn.hoverProperty().removeListener(hbarDecrementBtnHoverListener);\n }\n\n if(vbarIncrementBtnHoverListener!=null && vbarIncrementBtn!=null){\n vbarIncrementBtn.hoverProperty().removeListener(vbarIncrementBtnHoverListener);\n }\n\n if(vbarDecrementBtnHoverListener!=null && vbarDecrementBtn!=null){\n vbarDecrementBtn.hoverProperty().removeListener(vbarDecrementBtnHoverListener);\n }\n\n if(hbarThumbHoverListener!=null && hbarThumb!=null){\n hbarThumb.hoverProperty().removeListener(hbarThumbHoverListener);\n }\n\n if(vbarThumbHoverListener!=null && vbarThumb!=null){\n vbarThumb.hoverProperty().removeListener(vbarThumbHoverListener);\n }\n\n Paint paint = colorType.get().getPaint(),\n scrollBarArrowColor = FxKit.getOpacityPaint(paint, 0.5),\n scrollBarArrowHoverColor = FxKit.getOpacityPaint(paint, 0.85),\n scrollBarBackgroundColor = FxKit.getOpacityPaint(paint, 0.1),\n scrollBarThumbHoverColor = FxKit.getOpacityPaint(paint, 0.85),\n scrollBarThumbColor = FxKit.getOpacityPaint(paint, 0.5)\n ;\n\n Background btnBackground = new Background(new BackgroundFill(scrollBarArrowColor, new CornerRadii(0), Insets.EMPTY));\n Background btnHoverBackground = new Background(new BackgroundFill(scrollBarArrowHoverColor, new CornerRadii(0), Insets.EMPTY));\n Background trackBackground = new Background(new BackgroundFill(scrollBarBackgroundColor, new CornerRadii(0), Insets.EMPTY));\n\n// Insets ins = new Insets(0,2,0,2);\n// Background vbarThumbBackground = new Background(new BackgroundFill(scrollBarThumbColor, new CornerRadii(10), ins));\n// Background vbarThumbHoverBackground = new Background(new BackgroundFill(scrollBarThumbHoverColor, new CornerRadii(10), ins));\n//\n// Insets ins1 = new Insets(2,0,2,0);\n// Background hbarThumbBackground = new Background(new BackgroundFill(scrollBarThumbColor, new CornerRadii(10), ins1));\n// Background hbarThumbHoverBackground = new Background(new BackgroundFill(scrollBarThumbHoverColor, new CornerRadii(10), ins1));\n\n\n if(hbarIncrementArrow!=null) hbarIncrementArrow.setBackground(btnBackground);\n if(hbarDecrementArrow!=null) hbarDecrementArrow.setBackground(btnBackground);\n if(vbarIncrementArrow!=null) vbarIncrementArrow.setBackground(btnBackground);\n if(vbarDecrementArrow!=null) vbarDecrementArrow.setBackground(btnBackground);\n\n if(hbarBackground!=null) hbarBackground.setBackground(trackBackground);\n if(vbarBackground!=null) vbarBackground.setBackground(trackBackground);\n\n// hbarThumb.setBackground(hbarThumbBackground);\n// vbarThumb.setBackground(vbarThumbBackground);\n String thumbBg = scrollBarThumbColor.toString().replace(\"0x\", \"#\");\n String thumbBgHover = scrollBarThumbHoverColor.toString().replace(\"0x\", \"#\");\n if(hbarThumb!=null) hbarThumb.setStyle(\"-fx-background-color:\"+thumbBg+\";\");\n if(vbarThumb!=null) vbarThumb.setStyle(\"-fx-background-color:\"+thumbBg+\";\");\n\n if(hbarIncrementBtn != null){\n hbarIncrementBtnHoverListener = new ArrowBtnHoverListener(hbarIncrementBtn, hbarIncrementArrow, btnBackground, btnHoverBackground);\n hbarIncrementBtn.hoverProperty().addListener(hbarIncrementBtnHoverListener);\n }\n if(hbarDecrementBtn != null){\n hbarDecrementBtnHoverListener = new ArrowBtnHoverListener(hbarDecrementBtn, hbarDecrementArrow, btnBackground, btnHoverBackground);\n hbarDecrementBtn.hoverProperty().addListener(hbarDecrementBtnHoverListener);\n }\n\n if(vbarIncrementBtn!=null){\n vbarIncrementBtnHoverListener = new ArrowBtnHoverListener(vbarIncrementBtn, vbarIncrementArrow, btnBackground, btnHoverBackground);\n vbarIncrementBtn.hoverProperty().addListener(vbarIncrementBtnHoverListener);\n }\n\n if(vbarDecrementBtn!=null){\n vbarDecrementBtnHoverListener = new ArrowBtnHoverListener(vbarDecrementBtn, vbarDecrementArrow, btnBackground, btnHoverBackground);\n vbarDecrementBtn.hoverProperty().addListener(vbarDecrementBtnHoverListener);\n }\n\n if(hbarThumb!=null){\n hbarThumbHoverListener = new ThumbHoverListener(hbarThumb, thumbBg, thumbBgHover);\n hbarThumb.hoverProperty().addListener(hbarThumbHoverListener);\n }\n\n if(vbarThumb!=null){\n vbarThumbHoverListener = new ThumbHoverListener(vbarThumb, thumbBg, thumbBgHover);\n vbarThumb.hoverProperty().addListener(vbarThumbHoverListener);\n }\n\n }\n\n class ArrowBtnHoverListener implements ChangeListener<Boolean>{\n\n private Background background, hoverBackground;\n private Region incrementBtn, incrementArrow;\n\n public ArrowBtnHoverListener(Region incrementBtn, Region incrementArrow, Background background, Background hoverBackground){\n this.incrementBtn = incrementBtn;\n this.incrementArrow = incrementArrow;\n this.background = background;\n this.hoverBackground = hoverBackground;\n\n }\n\n @Override\n public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {\n if(newValue){\n incrementBtn.setScaleY(1.2);\n incrementBtn.setScaleX(1.2);\n incrementArrow.setBackground(hoverBackground);\n }else{\n incrementBtn.setScaleY(1);\n incrementBtn.setScaleX(1);\n incrementArrow.setBackground(background);\n }\n }\n }\n\n class ThumbHoverListener implements ChangeListener<Boolean>{\n private String background, hoverBackground;\n private Region thumb;\n public ThumbHoverListener(Region thumb, String background, String hoverBackground){\n this.thumb = thumb;\n this.background = background;\n this.hoverBackground = hoverBackground;\n }\n @Override\n public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {\n if(newValue){\n thumb.setStyle(\"-fx-background-color:\"+hoverBackground+\";\");\n }else{\n thumb.setStyle(\"-fx-background-color:\"+background+\";\");\n }\n }\n }\n\n}" } ]
import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.SizeType; import com.xm2013.jfx.control.base.VirtualFlowScrollHelper; import javafx.geometry.Insets; import javafx.scene.control.skin.ListViewSkin; import javafx.scene.layout.*;
3,737
/* * MIT License * * Copyright (c) 2023 [email protected] / wechat: t5x5m5 * * 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.xm2013.jfx.control.listview; public class XmListViewSkin<T> extends ListViewSkin<T> { private XmListView<T> control; public XmListViewSkin(XmListView<T> control) { super(control); this.control = control; updateSkin(); VirtualFlowScrollHelper helper = new VirtualFlowScrollHelper(getVirtualFlow()); helper.colorTypeProperty().bind(control.colorTypeProperty()); this.control.focusedProperty().addListener((ob, ov, nv)->{ setBackground(); }); registerChangeListener(control.sizeTypeProperty(), e -> updateSkin()); registerChangeListener(control.colorTypeProperty(), e->updateSkin()); registerChangeListener(control.hueTypeProperty(), e->updateSkin()); } private void updateSkin(){ SizeType sizeType = control.getSizeType(); double size = 40; if(SizeType.SMALL.equals(sizeType)){ size = 30; }else if(SizeType.LARGE.equals(sizeType)){ size = 50; } this.control.setFixedCellSize(size); setBackground(); } private void setBackground(){ Paint bgColor = null;
/* * MIT License * * Copyright (c) 2023 [email protected] / wechat: t5x5m5 * * 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.xm2013.jfx.control.listview; public class XmListViewSkin<T> extends ListViewSkin<T> { private XmListView<T> control; public XmListViewSkin(XmListView<T> control) { super(control); this.control = control; updateSkin(); VirtualFlowScrollHelper helper = new VirtualFlowScrollHelper(getVirtualFlow()); helper.colorTypeProperty().bind(control.colorTypeProperty()); this.control.focusedProperty().addListener((ob, ov, nv)->{ setBackground(); }); registerChangeListener(control.sizeTypeProperty(), e -> updateSkin()); registerChangeListener(control.colorTypeProperty(), e->updateSkin()); registerChangeListener(control.hueTypeProperty(), e->updateSkin()); } private void updateSkin(){ SizeType sizeType = control.getSizeType(); double size = 40; if(SizeType.SMALL.equals(sizeType)){ size = 30; }else if(SizeType.LARGE.equals(sizeType)){ size = 50; } this.control.setFixedCellSize(size); setBackground(); } private void setBackground(){ Paint bgColor = null;
HueType hueType = control.getHueType();
0
2023-10-17 08:57:08+00:00
8k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/controllers/EditorController.java
[ { "identifier": "AbstractJArmEmuModule", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/AbstractJArmEmuModule.java", "snippet": "public class AbstractJArmEmuModule implements Initializable {\n\n protected final JArmEmuApplication application;\n\n public AbstractJArmEmuModule(JArmEmuApplication application) {\n this.application = application;\n }\n\n protected JArmEmuApplication getApplication() {\n return application;\n }\n\n protected JArmEmuController getController() {\n return application.getController();\n }\n\n protected MainMenuController getMainMenuController() {\n return application.getMainMenuController();\n }\n\n protected MemoryDetailsController getMemoryDetailsController() {\n return application.getMemoryDetailsController();\n }\n protected MemoryOverviewController getMemoryOverviewController() {\n return application.getMemoryOverviewController();\n }\n\n protected RegistersController getRegistersController() {\n return application.getRegistersController();\n }\n\n protected SettingsController getSettingsController() {\n return application.getSettingsController();\n }\n\n protected StackController getStackController() {\n return application.getStackController();\n }\n\n protected SymbolsController getSymbolsController() {\n return application.getSymbolsController();\n }\n protected LabelsController getLabelsController() {\n return application.getLabelsController();\n }\n\n protected SourceParser getSourceParser() {\n return application.getSourceParser();\n }\n\n protected CodeInterpreter getCodeInterpreter() {\n return application.getCodeInterpreter();\n }\n\n protected ExecutionWorker getExecutionWorker() {\n return application.getExecutionWorker();\n }\n\n protected EditorController getEditorController() {\n return application.getEditorController();\n }\n\n protected SimulationMenuController getSimulationMenuController() {\n return application.getSimulationMenuController();\n }\n\n protected JArmEmuDialogs getDialogs() {\n return application.getDialogs();\n }\n\n @Override\n public void initialize(URL url, ResourceBundle resourceBundle) {\n\n }\n}" }, { "identifier": "JArmEmuApplication", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/JArmEmuApplication.java", "snippet": "public class JArmEmuApplication extends Application {\n\n public static final String OS_NAME = System.getProperty(\"os.name\").toLowerCase();\n public static final String OS_ARCH = System.getProperty(\"os.arch\").toLowerCase();\n public static final String OS_VERSION = System.getProperty(\"os.version\").toLowerCase();\n public static final String VERSION = JArmEmuApplication.class.getPackage().getImplementationVersion() != null ? JArmEmuApplication.class.getPackage().getImplementationVersion() : \"NotFound\" ;\n public static final Logger logger = Logger.getLogger(JArmEmuApplication.class.getName());\n\n // Controllers\n private JArmEmuController controller;\n\n private EditorController editorController;\n private MainMenuController mainMenuController;\n private MemoryDetailsController memoryDetailsController;\n private MemoryOverviewController memoryOverviewController;\n private RegistersController registersController;\n private SettingsController settingsController;\n private SimulationMenuController simulationMenuController;\n private StackController stackController;\n private SymbolsController symbolsController;\n private LabelsController labelsController;\n\n // Others\n private ShortcutHandler shortcutHandler;\n private SourceParser sourceParser;\n private CodeInterpreter codeInterpreter;\n private ExecutionWorker executionWorker;\n private JArmEmuDialogs dialogs;\n\n\n public Theme theme;\n public SimpleObjectProperty<Status> status;\n public Stage stage;\n public Scene scene;\n private String argSave;\n\n // TODO: Refaire les tests pour les initializers de données (pour un argument vide, plusieurs arguments, avec une section incorrecte etc)\n // TODO: Ajouter d'autres types de packages (ArchLinux, etc)\n\n @Override\n public void start(Stage stage) throws IOException {\n this.stage = stage;\n this.status = new SimpleObjectProperty<>(Status.INITIALIZING);\n\n logger.info(\"Starting up JArmEmu v\" + VERSION + \" on \" + OS_NAME + \" v\" + OS_VERSION + \" (\" + OS_ARCH + \")\");\n\n FXMLLoader fxmlLoader = new FXMLLoader(getResource(\"main-view.fxml\"));\n\n editorController = new EditorController(this);\n mainMenuController = new MainMenuController(this);\n memoryDetailsController = new MemoryDetailsController(this);\n memoryOverviewController = new MemoryOverviewController(this);\n registersController = new RegistersController(this);\n settingsController = new SettingsController(this);\n simulationMenuController = new SimulationMenuController(this);\n stackController = new StackController(this);\n symbolsController = new SymbolsController(this);\n labelsController = new LabelsController(this);\n dialogs = new JArmEmuDialogs(this);\n\n fxmlLoader.setController(new JArmEmuController(this));\n controller = fxmlLoader.getController();\n\n // Essayer d'ouvrir le fichier passé en paramètre\n if (!getParameters().getUnnamed().isEmpty()) {\n logger.info(\"Detecting file argument: \" + getParameters().getUnnamed().getFirst());\n argSave = getParameters().getUnnamed().getFirst();\n } else {\n argSave = null;\n }\n\n // Autres\n shortcutHandler = new ShortcutHandler(this);\n codeInterpreter = new CodeInterpreter();\n executionWorker = new ExecutionWorker(this);\n\n logger.info(\"Font \" + Font.loadFont(getResourceAsStream(\"fonts/Cantarell/Cantarell-Regular.ttf\"), 14).getFamily() + \" loaded\");\n logger.info(\"Font \" + Font.loadFont(getResourceAsStream(\"fonts/SourceCodePro/SourceCodePro-Regular.ttf\"), 14).getFamily() + \" loaded\");\n\n scene = new Scene(fxmlLoader.load(), 1280, 720);\n updateUserAgentStyle(getSettingsController().getThemeVariation(), getSettingsController().getThemeFamily());\n scene.getStylesheets().add(getResource(\"jarmemu-style.css\").toExternalForm());\n\n scene.setOnKeyPressed(shortcutHandler::handle);\n\n stage.setOnCloseRequest(this::onClosingRequest);\n stage.getIcons().addAll(\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/logo.png\"))\n );\n\n status.addListener((observable -> updateTitle()));\n getSimulationMenuController().onStop();\n\n updateTitle();\n stage.setScene(scene);\n stage.show();\n\n SplashScreen splashScreen = SplashScreen.getSplashScreen();\n\n int scale = (int) (stage.getOutputScaleY() * 100);\n Preferences.userRoot().node(getClass().getPackage().getName().replaceAll(\"\\\\.\", \"/\")).putInt(\"scale\", scale);\n logger.info(\"Computing scale: \" + scale + \"%\");\n\n if (splashScreen != null) {\n splashScreen.close();\n }\n\n logger.info(\"Startup finished\");\n status.set(Status.EDITING);\n }\n\n public void updateTitle() {\n stage.setTitle(\"JArmEmu v\" + VERSION + \" - \" + status.get());\n }\n\n /**\n * Mise à jour du UserAgentStyle pour la modification du thème.\n *\n * @param variation l'indice de la variation\n * @param family l'indice' de la famille\n */\n public void updateUserAgentStyle(int variation, int family) {\n if (family == 0) {\n theme = (variation == 0) ? new PrimerDark() : new PrimerLight();\n } else if (family == 1) {\n theme = (variation == 0) ? new NordDark() : new NordLight();\n } else {\n theme = (variation == 0) ? new CupertinoDark() : new CupertinoLight();\n }\n\n Application.setUserAgentStylesheet(theme.getUserAgentStylesheet());\n }\n\n /**\n * Définie l'état de maximisation.\n *\n * @param maximized l'état de maximisation\n */\n public void setMaximized(boolean maximized) {\n stage.setMaximized(maximized);\n }\n\n /**\n * @return l'état de maximisation\n */\n public boolean isMaximized() {\n return stage.isMaximized();\n }\n\n public ReadOnlyBooleanProperty maximizedProperty() {\n return stage.maximizedProperty();\n }\n\n /**\n * Adapte le splashscreen à la dimension de l'écran.\n *\n * @param splashScreen l'instance du splashscreen\n */\n private static void adaptSplashScreen(SplashScreen splashScreen) {\n try {\n int scale = Preferences.userRoot().node(JArmEmuApplication.class.getPackage().getName().replaceAll(\"\\\\.\", \"/\")).getInt(\"scale\", 100);\n\n logger.info(\"Adapting SplashScreen to current screen scale (\" + scale + \"%)\");\n\n URL url;\n \n if (scale >= 125 && scale < 150) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 150 && scale < 200) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 200 && scale < 250) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 250 && scale < 300) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 300) {\n url = getResource(\"jarmemu/medias/[email protected]\");\n } else {\n url = getResource(\"medias/splash.png\");\n }\n\n logger.info(\"Loading SplashScreen: \" + url);\n splashScreen.setImageURL(url);\n } catch (Exception e) {\n logger.severe(ExceptionUtils.getStackTrace(e));\n }\n }\n\n @Override\n public void stop() {\n\n }\n\n public static void main(String[] args) {\n System.setProperty(\"prism.dirtyopts\", \"false\");\n SplashScreen splashScreen = SplashScreen.getSplashScreen();\n\n if (splashScreen != null) {\n adaptSplashScreen(splashScreen);\n }\n\n JArmEmuApplication.launch(args);\n }\n\n public void openURL(String url) {\n getHostServices().showDocument(url);\n }\n\n public JArmEmuController getController() {\n return controller;\n }\n\n public MainMenuController getMainMenuController() {\n return mainMenuController;\n }\n\n public MemoryDetailsController getMemoryDetailsController() {\n return memoryDetailsController;\n }\n\n public MemoryOverviewController getMemoryOverviewController() {\n return memoryOverviewController;\n }\n\n public RegistersController getRegistersController() {\n return registersController;\n }\n\n public SettingsController getSettingsController() {\n return settingsController;\n }\n\n public StackController getStackController() {\n return stackController;\n }\n\n public SymbolsController getSymbolsController() {\n return symbolsController;\n }\n\n public LabelsController getLabelsController() {\n return labelsController;\n }\n\n public SourceParser getSourceParser() {\n return sourceParser;\n }\n\n public CodeInterpreter getCodeInterpreter() {\n return codeInterpreter;\n }\n\n public ExecutionWorker getExecutionWorker() {\n return executionWorker;\n }\n\n public EditorController getEditorController() {\n return editorController;\n }\n\n public SimulationMenuController getSimulationMenuController() {\n return simulationMenuController;\n }\n\n public JArmEmuDialogs getDialogs() {\n return dialogs;\n }\n\n private void onClosingRequest(WindowEvent event) {\n event.consume();\n getMainMenuController().onExit();\n }\n\n public void newSourceParser() {\n if (getSettingsController().getSourceParserSetting() == 1) {\n sourceParser = new LegacySourceParser(new SourceScanner(\"\", null, 0));\n } else {\n sourceParser = new RegexSourceParser(new SourceScanner(\"\", null, 0));\n }\n }\n\n /**\n * @param data les données\n * @param format le format (0, 1, 2)\n * @return une version formatée du nombre en données\n */\n public String getFormattedData(int data, int format) {\n if (format == 2) {\n return String.format(SettingsController.DATA_FORMAT_DICT[format], (long) data & 0xFFFFFFFFL).toUpperCase();\n } else {\n return String.format(SettingsController.DATA_FORMAT_DICT[format], data).toUpperCase();\n\n }\n }\n\n /**\n * @param data les données\n * @return une version formatée du nombre en données\n */\n public String getFormattedData(int data) {\n return getFormattedData(data, getSettingsController().getDataFormat());\n }\n\n /**\n * @return le chemin vers le fichier passé en paramètre (ou null si rien n'est passé en paramètre)\n */\n public String getArgSave() {\n return argSave;\n }\n\n public static @NotNull URL getResource(String name) {\n return Objects.requireNonNull(JArmEmuApplication.class.getResource(\"/fr/dwightstudio/jarmemu/\" + name));\n }\n\n public static @NotNull InputStream getResourceAsStream(String name) {\n return Objects.requireNonNull(JArmEmuApplication.class.getResourceAsStream(\"/fr/dwightstudio/jarmemu/\" + name));\n }\n}" }, { "identifier": "SourceScanner", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/SourceScanner.java", "snippet": "public class SourceScanner {\n\n private int currentInstructionValue;\n private final ArrayList<String> code;\n private final int fileIndex;\n private final String fileName;\n\n public SourceScanner(File file, int fileIndex) throws IOException {\n this.code = new ArrayList<>();\n BufferedReader reader = new BufferedReader(new FileReader(file));\n code.addAll(reader.lines().toList());\n this.currentInstructionValue = -1;\n this.fileIndex = fileIndex;\n fileName = file.getName();\n }\n\n public SourceScanner(String code, String fileName, int fileIndex) {\n this.code = new ArrayList<>(Arrays.stream(code.split(\"\\n\")).toList());\n this.currentInstructionValue = -1;\n this.fileIndex = fileIndex;\n this.fileName = fileName;\n }\n\n public String nextLine() {\n this.currentInstructionValue++;\n return this.code.get(this.currentInstructionValue);\n }\n\n public boolean hasNextLine() {\n return this.currentInstructionValue < this.code.size() - 1;\n }\n\n public void goTo(int lineNb) {\n this.currentInstructionValue = lineNb;\n }\n\n /**\n * Déplace le curseur de lecture à la ligne spécifiée. Attention, invalide le comptage d'instruction !\n */\n public String goToValue(int lineNb) {\n this.currentInstructionValue = lineNb;\n return this.code.get(this.currentInstructionValue);\n }\n\n public int getCurrentInstructionValue() {\n return this.currentInstructionValue;\n }\n\n public String exportCode() {\n return String.join(\"\\n\",code.toArray(String[]::new));\n }\n\n public void exportCodeToFile(File savePath) throws FileNotFoundException {\n PrintWriter printWriter = new PrintWriter(savePath);\n String last = \"\";\n for (String string : code) {\n printWriter.println(string);\n last = string;\n }\n if (!last.strip().equals(\"\")) printWriter.println(\"\");\n printWriter.close();\n }\n\n public int getFileIndex() {\n return fileIndex;\n }\n\n public String getName() {\n return fileName;\n }\n}" }, { "identifier": "SyntaxASMException", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/exceptions/SyntaxASMException.java", "snippet": "public class SyntaxASMException extends IllegalStateException {\n\n int line;\n ParsedObject parsedObject;\n private ParsedFile file;\n\n public SyntaxASMException(String s) {\n super(s);\n line = -1;\n }\n\n public boolean isLineSpecified() {\n return line != -1;\n }\n\n public boolean isFileSpecified() {\n return file != null;\n }\n\n public int getLine() {\n return line;\n }\n\n public ParsedFile getFile() {\n return file;\n }\n\n public void setLine(int line) {\n this.line = line;\n }\n\n public void setFile(ParsedFile file) {\n this.file = file;\n }\n\n public ParsedObject getObject() {\n return parsedObject;\n }\n\n public void setObject(ParsedObject obj) {\n this.parsedObject = obj;\n }\n\n public SyntaxASMException with(ParsedObject parsedObject) {\n this.parsedObject = parsedObject;\n return this;\n }\n\n public SyntaxASMException with(int line) {\n this.line = line;\n return this;\n }\n\n public SyntaxASMException with(ParsedFile file) {\n this.file = file;\n return this;\n }\n\n public String getTitle() {\n return \"Syntax error\";\n }\n}" }, { "identifier": "FilePos", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/FilePos.java", "snippet": "public class FilePos {\n public static final FilePos ZERO = new FilePos(0, 0).freeze();\n\n private int file;\n private int pos;\n\n public FilePos(int file, int pos) {\n this.file = file;\n this.pos = pos;\n }\n\n public FilePos(FilePos filePos) {\n this.file = filePos.file;\n this.pos = filePos.pos;\n }\n\n @Override\n public String toString() {\n return file + \":\" + pos;\n }\n\n public int getFileIndex() {\n return file;\n }\n\n public int getPos() {\n return pos;\n }\n\n public int incrementPos(int i) {\n return pos += i;\n }\n\n public int incrementPos() {\n return incrementPos(1);\n }\n\n public void setPos(int i) {\n pos = i;\n }\n\n public int incrementFileIndex(int i) {\n return file += i;\n }\n\n public int incrementFileIndex() {\n return incrementFileIndex(1);\n }\n\n public void setFileIndex(int i) {\n file = i;\n }\n\n public int toByteValue() {\n return pos * 4;\n }\n\n public FilePos freeze(int offset) {\n return new FrozenFilePos(this, offset);\n }\n\n public FilePos freeze() {\n return new FrozenFilePos(this, 0);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof FilePos position) {\n return position.getPos() == pos && position.getFileIndex() == file;\n } else {\n return false;\n }\n }\n\n public FilePos clone() {\n return new FilePos(this);\n }\n\n public static class FrozenFilePos extends FilePos {\n\n private final static String ERROR_MESSAGE = \"Can't modify frozen position\";\n\n private final int offset;\n\n\n public FrozenFilePos(FilePos filePos, int offset) {\n super(filePos.file, filePos.pos);\n this.offset = offset;\n }\n\n @Override\n public int getFileIndex() {\n return super.getFileIndex();\n }\n\n @Override\n public int getPos() {\n return super.getPos() + offset;\n }\n\n @Override\n public int incrementPos(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public void setPos(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public int incrementFileIndex(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public void setFileIndex(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public int toByteValue() {\n return getPos() * 4;\n }\n\n @Override\n public FilePos freeze() {\n return this;\n }\n }\n}" }, { "identifier": "FileUtils", "path": "src/main/java/fr/dwightstudio/jarmemu/util/FileUtils.java", "snippet": "public class FileUtils {\n public static boolean exists(File file) {\n if (file != null) {\n return file.exists();\n } else {\n return false;\n }\n }\n\n public static boolean isValidFile(File file) {\n if (exists(file)) {\n return file.isFile();\n } else {\n return false;\n }\n }\n}" } ]
import atlantafx.base.controls.Notification; import atlantafx.base.theme.Styles; import fr.dwightstudio.jarmemu.gui.AbstractJArmEmuModule; import fr.dwightstudio.jarmemu.gui.JArmEmuApplication; import fr.dwightstudio.jarmemu.sim.SourceScanner; import fr.dwightstudio.jarmemu.sim.exceptions.SyntaxASMException; import fr.dwightstudio.jarmemu.sim.obj.FilePos; import fr.dwightstudio.jarmemu.util.FileUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.material2.Material2OutlinedAL; import org.kordamp.ikonli.material2.Material2OutlinedMZ; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger;
5,655
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.controllers; public class EditorController extends AbstractJArmEmuModule { public static final String SAMPLE_CODE = String.join("\n", new String[]{".global _start", ".text", "_start:", "\t@ Beginning of the program"}); private final Logger logger = Logger.getLogger(getClass().getName()); private final ArrayList<FileEditor> fileEditors; private FileEditor lastScheduledEditor; private FileEditor lastExecutedEditor;
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.controllers; public class EditorController extends AbstractJArmEmuModule { public static final String SAMPLE_CODE = String.join("\n", new String[]{".global _start", ".text", "_start:", "\t@ Beginning of the program"}); private final Logger logger = Logger.getLogger(getClass().getName()); private final ArrayList<FileEditor> fileEditors; private FileEditor lastScheduledEditor; private FileEditor lastExecutedEditor;
public EditorController(JArmEmuApplication application) {
1
2023-10-17 18:22:09+00:00
8k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/container/ContainerMarket.java
[ { "identifier": "MessageMarketList", "path": "src/main/java/com/guigs44/farmingforengineers/network/MessageMarketList.java", "snippet": "public class MessageMarketList implements IMessage {\n\n private Collection<MarketEntry> entryList;\n\n public MessageMarketList() {}\n\n public MessageMarketList(Collection<MarketEntry> entryList) {\n this.entryList = entryList;\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n int entryCount = buf.readInt();\n entryList = Lists.newArrayListWithCapacity(entryCount);\n for (int i = 0; i < entryCount; i++) {\n entryList.add(readEntry(buf));\n }\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n int count = entryList.size();\n buf.writeInt(count);\n for (MarketEntry recipe : entryList) {\n writeEntry(recipe, buf);\n }\n }\n\n public Collection<MarketEntry> getEntryList() {\n return entryList;\n }\n\n private MarketEntry readEntry(ByteBuf buf) {\n ItemStack outputItem = ByteBufUtils.readItemStack(buf);\n ItemStack costItem = ByteBufUtils.readItemStack(buf);\n MarketEntry.EntryType type = MarketEntry.EntryType.fromId(buf.readByte());\n return new MarketEntry(outputItem, costItem, type);\n }\n\n private void writeEntry(MarketEntry entry, ByteBuf buf) {\n ByteBufUtils.writeItemStack(buf, entry.getOutputItem());\n ByteBufUtils.writeItemStack(buf, entry.getCostItem());\n buf.writeByte(entry.getType().ordinal());\n }\n}" }, { "identifier": "NetworkHandler", "path": "src/main/java/com/guigs44/farmingforengineers/network/NetworkHandler.java", "snippet": "public class NetworkHandler {\n\n public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE\n .newSimpleChannel(FarmingForEngineers.MOD_ID);\n\n public static void init() {\n instance.registerMessage(HandlerMarketList.class, MessageMarketList.class, 0, Side.CLIENT);\n instance.registerMessage(HandlerMarketSelect.class, MessageMarketSelect.class, 1, Side.SERVER);\n }\n\n // public static Minecraft getThreadListener(MessageContext ctx) {\n // return ctx.side == Side.SERVER ? ctx.getServerHandler().playerEntity.worldObj : getClientThreadListener();\n // }\n\n @SideOnly(Side.CLIENT)\n public static Minecraft getClientThreadListener() {\n return Minecraft.getMinecraft();\n }\n}" }, { "identifier": "MarketEntry", "path": "src/main/java/com/guigs44/farmingforengineers/registry/MarketEntry.java", "snippet": "public class MarketEntry {\n\n public enum EntryType {\n\n SEEDS(\"gui.farmingforengineers:market.tooltip_seeds\"),\n SAPLINGS(\"gui.farmingforengineers:market.tooltip_saplings\"),\n OTHER(\"gui.farmingforengineers:market.tooltip_other\");\n\n private static final ResourceLocation TEXTURE = new ResourceLocation(\n FarmingForEngineers.MOD_ID,\n \"textures/gui/market.png\");\n private static final EntryType[] values = values();\n private String tooltip;\n\n EntryType(String tooltip) {\n this.tooltip = tooltip;\n }\n\n public String getTooltip() {\n return tooltip;\n }\n\n public ResourceLocation getIconTexture() {\n return TEXTURE;\n }\n\n public int getIconTextureX() {\n return 196 + ordinal() * 20;\n }\n\n public int getIconTextureY() {\n return 14;\n }\n\n public boolean passes(MarketEntry entry) {\n return entry.getType() == this;\n }\n\n public static EntryType fromId(int id) {\n return values[id];\n }\n }\n\n private final ItemStack outputItem;\n private final ItemStack costItem;\n private final EntryType type;\n\n public MarketEntry(ItemStack outputItem, ItemStack costItem, EntryType type) {\n this.outputItem = outputItem;\n this.costItem = costItem;\n this.type = type;\n }\n\n public ItemStack getCostItem() {\n return costItem;\n }\n\n public ItemStack getOutputItem() {\n return outputItem;\n }\n\n public EntryType getType() {\n return type;\n }\n}" }, { "identifier": "MarketRegistry", "path": "src/main/java/com/guigs44/farmingforengineers/registry/MarketRegistry.java", "snippet": "public class MarketRegistry extends AbstractRegistry {\n\n public static final MarketRegistry INSTANCE = new MarketRegistry();\n\n private static final Pattern ITEMSTACK_PATTERN = Pattern\n .compile(\"(?:([0-9]+)\\\\*)?(?:([\\\\w]+):)([\\\\w]+)(?::([0-9]+))?(?:@(.+))?\");\n\n private final List<MarketEntry> entries = Lists.newArrayList();\n\n private final Map<String, ItemStack> defaultPayments = Maps.newHashMap();\n private final Map<String, MarketRegistryDefaultHandler> defaultHandlers = Maps.newHashMap();\n\n public MarketRegistry() {\n super(\"Market\");\n }\n\n public void registerEntry(ItemStack outputItem, ItemStack costItem, MarketEntry.EntryType type) {\n entries.add(new MarketEntry(outputItem, costItem, type));\n }\n\n @Nullable\n public static MarketEntry getEntryFor(ItemStack outputItem) {\n for (MarketEntry entry : INSTANCE.entries) {\n if (entry.getOutputItem().isItemEqual(outputItem)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), outputItem)) {\n return entry;\n }\n }\n return null;\n }\n\n public static Collection<MarketEntry> getEntries() {\n return INSTANCE.entries;\n }\n\n @Override\n protected void clear() {\n entries.clear();\n }\n\n @Override\n protected JsonObject create() {\n JsonObject root = new JsonObject();\n\n JsonObject defaults = new JsonObject();\n defaults.addProperty(\n \"__comment\",\n \"You can disable defaults by setting these to false. Do *NOT* try to add additional entries here. You can add additional entries in the custom section.\");\n root.add(\"defaults\", defaults);\n\n JsonObject payment = new JsonObject();\n payment.addProperty(\"__comment\", \"You can define custom payment items for the default entries here.\");\n root.add(\"defaults payment\", payment);\n\n JsonArray blacklist = new JsonArray();\n blacklist.add(new JsonPrimitive(\"examplemod:example_item\"));\n root.add(\"defaults blacklist\", blacklist);\n\n JsonObject custom = new JsonObject();\n custom.addProperty(\n \"__comment\",\n \"You can define additional items to be sold by the Market here. Defaults can be overridden. Prefix with ! to blacklist instead.\");\n custom.addProperty(\"examplemod:example_item\", \"2*minecraft:emerald\");\n root.add(\"custom entries\", custom);\n\n return root;\n }\n\n @Override\n protected void load(JsonObject root) {\n JsonObject payments = tryGetObject(root, \"defaults payment\");\n loadDefaultPayments(payments);\n\n JsonObject defaults = tryGetObject(root, \"defaults\");\n registerDefaults(defaults);\n\n JsonArray blacklist = tryGetArray(root, \"defaults blacklist\");\n for (int i = 0; i < blacklist.size(); i++) {\n JsonElement element = blacklist.get(i);\n if (element.isJsonPrimitive()) {\n loadDefaultBlacklistEntry(element.getAsString());\n } else {\n logError(\"Failed to load %s registry: blacklist entries must be strings\", registryName);\n }\n }\n\n JsonObject custom = tryGetObject(root, \"custom entries\");\n for (Map.Entry<String, JsonElement> entry : custom.entrySet()) {\n if (entry.getValue().isJsonPrimitive()) {\n loadMarketEntry(entry.getKey(), entry.getValue().getAsString());\n } else {\n logError(\"Failed to load %s registry: entries must be strings\", registryName);\n }\n }\n }\n\n @Override\n protected boolean hasCustomLoader() {\n return true;\n }\n\n private void loadMarketEntry(String key, String value) {\n if (key.equals(\"__comment\") || key.equals(\"examplemod:example_item\")) {\n return;\n }\n\n ItemStack outputStack = parseItemStack(key);\n ItemStack costStack = parseItemStack(value);\n if (outputStack == null || costStack == null) {\n return;\n }\n\n tryRemoveEntry(outputStack);\n\n MarketEntry.EntryType type = MarketEntry.EntryType.OTHER;\n\n // outputStack.getItem().getRegistryName().getResourcePath().contains(\"sapling\") maybe\n if (outputStack.getItem().getUnlocalizedName().contains(\"sapling\")) {\n type = MarketEntry.EntryType.SAPLINGS;\n } else if (outputStack.getItem().getUnlocalizedName().contains(\"seed\")) {\n type = MarketEntry.EntryType.SEEDS;\n }\n\n registerEntry(outputStack, costStack, type);\n }\n\n private void loadDefaultBlacklistEntry(String input) {\n if (input.equals(\"examplemod:example_item\")) {\n return;\n }\n ItemStack itemStack = parseItemStack(input);\n if (itemStack != null) {\n if (!tryRemoveEntry(itemStack)) {\n logError(\"Could not find default entry for blacklisted item %s\", input);\n }\n }\n }\n\n private void loadDefaultPayments(JsonObject defaults) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n String value = tryGetString(defaults, entry.getKey(), \"\");\n if (value.isEmpty()) {\n ItemStack defaultPayment = entry.getValue().getDefaultPayment();\n defaults.addProperty(\n entry.getKey(),\n String.format(\n \"%d*%s:%d\",\n defaultPayment.stackSize,\n defaultPayment.getItem().getUnlocalizedName(),\n defaultPayment.getItemDamage()));\n }\n ItemStack itemStack = !value.isEmpty() ? parseItemStack(value) : null;\n if (itemStack == null) {\n itemStack = entry.getValue().getDefaultPayment();\n }\n defaultPayments.put(entry.getKey(), itemStack);\n }\n }\n\n @Override\n protected void registerDefaults(JsonObject json) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n if (tryGetBoolean(json, entry.getKey(), entry.getValue().isEnabledByDefault())) {\n entry.getValue().apply(this, INSTANCE.defaultPayments.get(entry.getKey()));\n }\n }\n }\n\n public static void registerDefaultHandler(String defaultKey, MarketRegistryDefaultHandler handler) {\n INSTANCE.defaultHandlers.put(defaultKey, handler);\n }\n\n private boolean tryRemoveEntry(ItemStack itemStack) {\n for (int i = entries.size() - 1; i >= 0; i--) {\n MarketEntry entry = entries.get(i);\n if (entry.getOutputItem().isItemEqual(itemStack)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), itemStack)) {\n entries.remove(i);\n return true;\n }\n }\n return false;\n }\n\n @Nullable\n private ItemStack parseItemStack(String input) {\n Matcher matcher = ITEMSTACK_PATTERN.matcher(input);\n if (!matcher.find()) {\n logError(\"Invalid item %s, format mismatch\", input);\n return null;\n }\n\n ResourceLocation resourceLocation = new ResourceLocation(matcher.group(2), matcher.group(3));\n Item item = (Item) Item.itemRegistry.getObject(resourceLocation.toString());\n if (item == null) {\n logUnknownItem(resourceLocation);\n return null;\n }\n int count = matcher.group(1) != null ? tryParseInt(matcher.group(1)) : 1;\n int meta = matcher.group(4) != null ? tryParseInt(matcher.group(4)) : 0;\n String nbt = matcher.group(5);\n NBTTagCompound tagCompound = null;\n if (nbt != null) {\n tagCompound = (NBTTagCompound) codechicken.nei.util.NBTJson.toNbt(JsonParser.parseString(nbt));\n }\n ItemStack itemStack = new ItemStack(item, count, meta);\n if (tagCompound != null) {\n itemStack.setTagCompound(tagCompound);\n }\n return itemStack;\n }\n}" } ]
import java.util.List; import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import com.google.common.collect.Lists; import com.guigs44.farmingforengineers.network.MessageMarketList; import com.guigs44.farmingforengineers.network.NetworkHandler; import com.guigs44.farmingforengineers.registry.MarketEntry; import com.guigs44.farmingforengineers.registry.MarketRegistry;
3,891
package com.guigs44.farmingforengineers.container; public class ContainerMarket extends Container { private final EntityPlayer player; private final int posX; private final int posY; private final int posZ; private final InventoryBasic marketInputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); private final InventoryBasic marketOutputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList(); private boolean sentItemList; protected MarketEntry selectedEntry; public ContainerMarket(EntityPlayer player, int posX, int posY, int posZ) { this.player = player; this.posX = posX; this.posY = posY; this.posZ = posZ; addSlotToContainer(new Slot(marketInputBuffer, 0, 23, 39)); addSlotToContainer(new SlotMarketBuy(this, marketOutputBuffer, 0, 61, 39)); for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { FakeSlotMarket slot = new FakeSlotMarket(j + i * 3, 102 + j * 18, 11 + i * 18); marketSlots.add(slot); addSlotToContainer(slot); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 92 + i * 18)); } } for (int i = 0; i < 9; i++) { addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 150)); } } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { ItemStack itemStack = null; Slot slot = (Slot) this.inventorySlots.get(slotIndex); if (slot != null && slot.getHasStack()) { ItemStack slotStack = slot.getStack(); // noinspection ConstantConditions itemStack = slotStack.copy(); if (slotIndex == 1) { if (!this.mergeItemStack(slotStack, 14, 50, true)) { return null; } slot.onSlotChange(slotStack, itemStack); } else if (slotIndex == 0) { if (!mergeItemStack(slotStack, 14, 50, true)) { return null; } } else if ((selectedEntry == null && slotStack.getItem() == Items.emerald) || (selectedEntry != null && selectedEntry.getCostItem().isItemEqual(slotStack))) { if (!this.mergeItemStack(slotStack, 0, 1, true)) { return null; } } else if (slotIndex >= 41 && slotIndex < 50) { if (!mergeItemStack(slotStack, 14, 41, true)) { return null; } } else if (slotIndex >= 14 && slotIndex < 41) { if (!mergeItemStack(slotStack, 41, 50, false)) { return null; } } if (slotStack.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } if (slotStack.stackSize == itemStack.stackSize) { return null; } slot.onPickupFromSlot(player, slotStack); } return itemStack; } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); if (!player.worldObj.isRemote && !sentItemList) {
package com.guigs44.farmingforengineers.container; public class ContainerMarket extends Container { private final EntityPlayer player; private final int posX; private final int posY; private final int posZ; private final InventoryBasic marketInputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); private final InventoryBasic marketOutputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList(); private boolean sentItemList; protected MarketEntry selectedEntry; public ContainerMarket(EntityPlayer player, int posX, int posY, int posZ) { this.player = player; this.posX = posX; this.posY = posY; this.posZ = posZ; addSlotToContainer(new Slot(marketInputBuffer, 0, 23, 39)); addSlotToContainer(new SlotMarketBuy(this, marketOutputBuffer, 0, 61, 39)); for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { FakeSlotMarket slot = new FakeSlotMarket(j + i * 3, 102 + j * 18, 11 + i * 18); marketSlots.add(slot); addSlotToContainer(slot); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 92 + i * 18)); } } for (int i = 0; i < 9; i++) { addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 150)); } } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { ItemStack itemStack = null; Slot slot = (Slot) this.inventorySlots.get(slotIndex); if (slot != null && slot.getHasStack()) { ItemStack slotStack = slot.getStack(); // noinspection ConstantConditions itemStack = slotStack.copy(); if (slotIndex == 1) { if (!this.mergeItemStack(slotStack, 14, 50, true)) { return null; } slot.onSlotChange(slotStack, itemStack); } else if (slotIndex == 0) { if (!mergeItemStack(slotStack, 14, 50, true)) { return null; } } else if ((selectedEntry == null && slotStack.getItem() == Items.emerald) || (selectedEntry != null && selectedEntry.getCostItem().isItemEqual(slotStack))) { if (!this.mergeItemStack(slotStack, 0, 1, true)) { return null; } } else if (slotIndex >= 41 && slotIndex < 50) { if (!mergeItemStack(slotStack, 14, 41, true)) { return null; } } else if (slotIndex >= 14 && slotIndex < 41) { if (!mergeItemStack(slotStack, 41, 50, false)) { return null; } } if (slotStack.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } if (slotStack.stackSize == itemStack.stackSize) { return null; } slot.onPickupFromSlot(player, slotStack); } return itemStack; } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); if (!player.worldObj.isRemote && !sentItemList) {
NetworkHandler.instance.sendTo(new MessageMarketList(MarketRegistry.getEntries()), (EntityPlayerMP) player);
0
2023-10-17 00:25:50+00:00
8k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/util/functional/FunctionalUtils.java
[ { "identifier": "CollectionUtils", "path": "src/berkeley_parser/edu/berkeley/nlp/util/CollectionUtils.java", "snippet": "public class CollectionUtils {\n\n\tpublic interface CollectionFactory<V> {\n\n\t\tCollection<V> newCollection();\n\n\t}\n\n\tpublic static <E extends Comparable<E>> List<E> sort(Collection<E> c) {\n\t\tList<E> list = new ArrayList<E>(c);\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}\n\n\tpublic static <E> boolean isSublistOf(List<E> bigger, List<E> smaller) {\n\t\tif (smaller.size() > bigger.size())\n\t\t\treturn false;\n\t\tfor (int start = 0; start + smaller.size() <= bigger.size(); ++start) {\n\t\t\tList<E> sublist = bigger.subList(start, start + smaller.size());\n\t\t\tif (sublist.equals(bigger)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static <E> List<E> sort(Collection<E> c, Comparator<E> r) {\n\t\tList<E> list = new ArrayList<E>(c);\n\t\tCollections.sort(list, r);\n\t\treturn list;\n\t}\n\n\tpublic static <K, V> void addToValueSet(Map<K, Set<V>> map, K key, V value) {\n\t\taddToValueSet(map, key, value, new SetFactory.HashSetFactory<V>());\n\t}\n\n\tpublic static <K, V extends Comparable<V>> void addToValueSortedSet(\n\t\t\tMap<K, SortedSet<V>> map, K key, V value) {\n\t\tSortedSet<V> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = new TreeSet<V>();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.add(value);\n\t}\n\n\tpublic static <K, V> void addToValueSet(Map<K, Set<V>> map, K key, V value,\n\t\t\tSetFactory<V> mf) {\n\t\tSet<V> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = mf.buildSet();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.add(value);\n\t}\n\n\tpublic static <K, V, T> Map<V, T> addToValueMap(Map<K, Map<V, T>> map,\n\t\t\tK key, V value, T value2) {\n\t\treturn addToValueMap(map, key, value, value2,\n\t\t\t\tnew MapFactory.HashMapFactory<V, T>());\n\t}\n\n\tpublic static <K, V, T> Map<V, T> addToValueMap(Map<K, Map<V, T>> map,\n\t\t\tK key, V value, T value2, MapFactory<V, T> mf) {\n\t\tMap<V, T> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = mf.buildMap();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.put(value, value2);\n\t\treturn values;\n\t}\n\n\tpublic static <K, V> void addToValueList(Map<K, List<V>> map, K key, V value) {\n\t\tList<V> valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = new ArrayList<V>();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V> void addToValueCollection(Map<K, Collection<V>> map,\n\t\t\tK key, V value, CollectionFactory<V> cf) {\n\t\tCollection<V> valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = cf.newCollection();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V, C extends Collection<V>> void addToValueCollection(\n\t\t\tMap<K, C> map, K key, V value, Factory<C> fact) {\n\t\tC valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = fact.newInstance();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V> List<V> getValueList(Map<K, List<V>> map, K key) {\n\t\tList<V> valueList = map.get(key);\n\t\tif (valueList == null)\n\t\t\treturn Collections.emptyList();\n\t\treturn valueList;\n\t}\n\n\tpublic static <K, V> Set<V> getValueSet(Map<K, Set<V>> map, K key) {\n\t\tSet<V> valueSet = map.get(key);\n\t\tif (valueSet == null)\n\t\t\treturn Collections.emptySet();\n\t\treturn valueSet;\n\t}\n\n\tpublic static <T> List<T> makeList(T... args) {\n\t\treturn new ArrayList<T>(Arrays.asList(args));\n\t}\n\n\tpublic static <T> Set<T> makeSet(T... args) {\n\t\treturn new HashSet<T>(Arrays.asList(args));\n\t}\n\n\tpublic static <T> void quicksort(T[] array, Comparator<? super T> c) {\n\n\t\tquicksort(array, 0, array.length - 1, c);\n\n\t}\n\n\tpublic static <T> void quicksort(T[] array, int left0, int right0,\n\t\t\tComparator<? super T> c) {\n\n\t\tint left, right;\n\t\tT pivot, temp;\n\t\tleft = left0;\n\t\tright = right0 + 1;\n\n\t\tfinal int pivotIndex = (left0 + right0) / 2;\n\t\tpivot = array[pivotIndex];\n\t\ttemp = array[left0];\n\t\tarray[left0] = pivot;\n\t\tarray[pivotIndex] = temp;\n\n\t\tdo {\n\n\t\t\tdo\n\t\t\t\tleft++;\n\t\t\twhile (left <= right0 && c.compare(array[left], pivot) < 0);\n\n\t\t\tdo\n\t\t\t\tright--;\n\t\t\twhile (c.compare(array[right], pivot) > 0);\n\n\t\t\tif (left < right) {\n\t\t\t\ttemp = array[left];\n\t\t\t\tarray[left] = array[right];\n\t\t\t\tarray[right] = temp;\n\t\t\t}\n\n\t\t} while (left <= right);\n\n\t\ttemp = array[left0];\n\t\tarray[left0] = array[right];\n\t\tarray[right] = temp;\n\n\t\tif (left0 < right)\n\t\t\tquicksort(array, left0, right, c);\n\t\tif (left < right0)\n\t\t\tquicksort(array, left, right0, c);\n\n\t}\n\n\tpublic static <S, T> Iterable<Pair<S, T>> getPairIterable(\n\t\t\tfinal Iterable<S> sIterable, final Iterable<T> tIterable) {\n\t\treturn new Iterable<Pair<S, T>>() {\n\t\t\tpublic Iterator<Pair<S, T>> iterator() {\n\t\t\t\tclass PairIterator implements Iterator<Pair<S, T>> {\n\n\t\t\t\t\tprivate Iterator<S> sIterator;\n\n\t\t\t\t\tprivate Iterator<T> tIterator;\n\n\t\t\t\t\tprivate PairIterator() {\n\t\t\t\t\t\tsIterator = sIterable.iterator();\n\t\t\t\t\t\ttIterator = tIterable.iterator();\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\treturn sIterator.hasNext() && tIterator.hasNext();\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic Pair<S, T> next() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\treturn Pair.newPair(sIterator.next(), tIterator.next());\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic void remove() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\tsIterator.remove();\n\t\t\t\t\t\ttIterator.remove();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t;\n\t\t\t\treturn new PairIterator();\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic static <T> List<T> doubletonList(T t1, T t2) {\n\t\treturn new DoubletonList(t1, t2);\n\t}\n\n\tpublic static class MutableSingletonSet<E> extends AbstractSet<E> implements\n\t\t\tSerializable {\n\t\tprivate final class MutableSingletonSetIterator implements Iterator<E> {\n\t\t\tprivate boolean hasNext = true;\n\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn hasNext;\n\t\t\t}\n\n\t\t\tpublic E next() {\n\t\t\t\tif (hasNext) {\n\t\t\t\t\thasNext = false;\n\t\t\t\t\treturn element;\n\t\t\t\t}\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\t}\n\n\t\t\tpublic void remove() {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\n\t\t\tpublic void reset() {\n\t\t\t\thasNext = true;\n\n\t\t\t}\n\t\t}\n\n\t\t// use serialVersionUID from JDK 1.2.2 for interoperability\n\t\tprivate static final long serialVersionUID = 3193687207550431679L;\n\n\t\tprivate E element;\n\n\t\tprivate final MutableSingletonSetIterator iter;\n\n\t\tpublic MutableSingletonSet(E o) {\n\t\t\telement = o;\n\t\t\tthis.iter = new MutableSingletonSetIterator();\n\t\t}\n\n\t\tpublic void set(E o) {\n\t\t\telement = o;\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<E> iterator() {\n\t\t\titer.reset();\n\t\t\treturn iter;\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn 1;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object o) {\n\t\t\treturn eq(o, element);\n\t\t}\n\t}\n\n\tprivate static class DoubletonList<E> extends AbstractList<E> implements\n\t\t\tRandomAccess, Serializable {\n\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = -8444118491195689776L;\n\n\t\tprivate final E element1;\n\n\t\tprivate final E element2;\n\n\t\tDoubletonList(E e1, E e2) {\n\t\t\telement1 = e1;\n\t\t\telement2 = e2;\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn 2;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object obj) {\n\t\t\treturn eq(obj, element1) || eq(obj, element2);\n\t\t}\n\n\t\t@Override\n\t\tpublic E get(int index) {\n\t\t\tif (index == 0)\n\t\t\t\treturn element1;\n\t\t\tif (index == 1)\n\t\t\t\treturn element2;\n\n\t\t\tthrow new IndexOutOfBoundsException(\"Index: \" + index + \", Size: 2\");\n\t\t}\n\t}\n\n\tprivate static boolean eq(Object o1, Object o2) {\n\t\treturn (o1 == null ? o2 == null : o1.equals(o2));\n\t}\n\n\tpublic static <K, V, V2> Map<V, V2> getOrCreateMap(Map<K, Map<V, V2>> map,\n\t\t\tK key) {\n\t\tMap<V, V2> r = map.get(key);\n\t\tif (r == null)\n\t\t\tmap.put(key, r = new HashMap<V, V2>());\n\t\treturn r;\n\t}\n\n\tpublic static Map getMapFromString(String s, Class keyClass,\n\t\t\tClass valueClass, MapFactory mapFactory)\n\t\t\tthrows ClassNotFoundException, NoSuchMethodException,\n\t\t\tIllegalAccessException, InvocationTargetException,\n\t\t\tInstantiationException {\n\t\tConstructor keyC = keyClass.getConstructor(new Class[] { Class\n\t\t\t\t.forName(\"java.lang.String\") });\n\t\tConstructor valueC = valueClass.getConstructor(new Class[] { Class\n\t\t\t\t.forName(\"java.lang.String\") });\n\t\tif (s.charAt(0) != '{')\n\t\t\tthrow new RuntimeException(\"\");\n\t\ts = s.substring(1); // get rid of first brace\n\t\tString[] fields = s.split(\"\\\\s+\");\n\t\tMap m = mapFactory.buildMap();\n\t\t// populate m\n\t\tfor (int i = 0; i < fields.length; i++) {\n\t\t\t// System.err.println(\"Parsing \" + fields[i]);\n\t\t\tfields[i] = fields[i].substring(0, fields[i].length() - 1); // get\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// rid\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// of\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// following\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// comma\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// or\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// brace\n\t\t\tString[] a = fields[i].split(\"=\");\n\t\t\tObject key = keyC.newInstance(a[0]);\n\t\t\tObject value;\n\t\t\tif (a.length > 1) {\n\t\t\t\tvalue = valueC.newInstance(a[1]);\n\t\t\t} else {\n\t\t\t\tvalue = \"\";\n\t\t\t}\n\t\t\tm.put(key, value);\n\t\t}\n\t\treturn m;\n\t}\n\n\tpublic static <T> List<T> concatenateLists(List<? extends T>... lst) {\n\t\tList<T> finalList = new ArrayList<T>();\n\t\tfor (List<? extends T> ts : lst) {\n\t\t\tfinalList.addAll(ts);\n\t\t}\n\t\treturn finalList;\n\n\t}\n\n\tpublic static <T> List<T> truncateList(List<T> lst, int maxTrainDocs) {\n\t\tif (maxTrainDocs < lst.size()) {\n\t\t\treturn lst.subList(0, maxTrainDocs);\n\t\t}\n\t\treturn lst;\n\t}\n\n\t/**\n\t * Differs from Collections.shuffle by NOT being in place\n\t * \n\t * @param items\n\t * @param rand\n\t * @param <T>\n\t * @return\n\t */\n\tpublic static <T> List<T> shuffle(Collection<T> items, Random rand) {\n\t\tList<T> shuffled = new ArrayList(items);\n\t\tCollections.shuffle(shuffled, rand);\n\t\treturn shuffled;\n\t}\n\n}" }, { "identifier": "Factory", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Factory.java", "snippet": "public interface Factory<T> {\n\tT newInstance(Object... args);\n\n\tpublic static class DefaultFactory<T> implements Factory<T> {\n\t\tprivate final Class c;\n\n\t\tpublic DefaultFactory(Class c) {\n\t\t\tthis.c = c;\n\t\t}\n\n\t\tpublic T newInstance(Object... args) {\n\t\t\ttry {\n\t\t\t\treturn (T) c.newInstance();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" }, { "identifier": "LazyIterable", "path": "src/berkeley_parser/edu/berkeley/nlp/util/LazyIterable.java", "snippet": "public class LazyIterable<T, I> implements Iterable<T> {\n\n\tprivate Iterable<I> inputIterable;\n\tprivate Function<I, ? extends T> factory;\n\tprivate int cacheSize;\n\tprivate Predicate<T> outputPred;\n\tprivate Set<I> rejectedInputs;\n\n\tpublic LazyIterable(Iterable<I> inputIterable,\n\t\t\tFunction<I, ? extends T> factory, Predicate<T> outputPred,\n\t\t\tint cacheSize) {\n\t\tthis.inputIterable = inputIterable;\n\t\tthis.factory = factory;\n\t\tthis.cacheSize = cacheSize;\n\t\tthis.outputPred = outputPred;\n\t\tthis.rejectedInputs = new HashSet<I>();\n\t}\n\n\tprivate class MyIterator implements Iterator<T> {\n\n\t\tprivate Iterator<I> inputIt;\n\t\tprivate Queue<T> cache;\n\n\t\tvoid ensure() {\n\t\t\t// if (cache == null) cache = new ArrayDeque<T>();\n\t\t\tif (!cache.isEmpty())\n\t\t\t\treturn;\n\t\t\twhile (cache.size() < cacheSize && inputIt.hasNext()) {\n\t\t\t\tT next = nextInternal();\n\t\t\t\tcache.add(next);\n\t\t\t}\n\t\t}\n\n\t\tT nextInternal() {\n\t\t\twhile (inputIt.hasNext()) {\n\t\t\t\tI input = inputIt.next();\n\t\t\t\tif (rejectedInputs.contains(input)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tT output = factory.apply(input);\n\t\t\t\tif (outputPred.apply(output)) {\n\t\t\t\t\treturn output;\n\t\t\t\t} else {\n\t\t\t\t\trejectedInputs.add(input);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tMyIterator() {\n\t\t\tinputIt = inputIterable.iterator();\n\t\t}\n\n\t\tpublic boolean hasNext() {\n\t\t\treturn inputIt.hasNext() || !cache.isEmpty();\n\t\t}\n\n\t\tpublic T next() {\n\t\t\tensure();\n\t\t\treturn cache.poll();\n\t\t}\n\n\t\tpublic void remove() {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic Iterator<T> iterator() {\n\t\treturn new MyIterator();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tList<String> arr = CollectionUtils.makeList(\"Aria is cool\", \"Isn't he\");\n\t\tFunction<String, String[]> factory = new Function<String, String[]>() {\n\t\t\tpublic String[] apply(String input) {\n\t\t\t\treturn input.split(\"\\\\s+\");\n\t\t\t}\n\t\t};\n\t\tIterable<String[]> iterable = new LazyIterable<String[], String>(arr,\n\t\t\t\tfactory, null, 10);\n\t\tfor (String[] strings : iterable) {\n\t\t\tSystem.out.println(Arrays.deepToString(strings));\n\t\t}\n\t}\n}" }, { "identifier": "Pair", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Pair.java", "snippet": "public class Pair<F, S> implements Serializable {\n\tstatic final long serialVersionUID = 42;\n\n\tF first;\n\tS second;\n\n\tpublic F getFirst() {\n\t\treturn first;\n\t}\n\n\tpublic S getSecond() {\n\t\treturn second;\n\t}\n\n\tpublic void setFirst(F pFirst) {\n\t\tfirst = pFirst;\n\t}\n\n\tpublic void setSecond(S pSecond) {\n\t\tsecond = pSecond;\n\t}\n\n\tpublic Pair<S, F> reverse() {\n\t\treturn new Pair<S, F>(second, first);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (!(o instanceof Pair))\n\t\t\treturn false;\n\n\t\tfinal Pair pair = (Pair) o;\n\n\t\tif (first != null ? !first.equals(pair.first) : pair.first != null)\n\t\t\treturn false;\n\t\tif (second != null ? !second.equals(pair.second) : pair.second != null)\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint result;\n\t\tresult = (first != null ? first.hashCode() : 0);\n\t\tresult = 29 * result + (second != null ? second.hashCode() : 0);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + getFirst() + \", \" + getSecond() + \")\";\n\t}\n\n\tpublic Pair(F first, S second) {\n\t\tthis.first = first;\n\t\tthis.second = second;\n\t}\n\n\t// Compares only first values\n\tpublic static class FirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getFirst().compareTo(p2.getFirst());\n\t\t}\n\t}\n\n\tpublic static class ReverseFirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getFirst().compareTo(p1.getFirst());\n\t\t}\n\t}\n\n\t// Compares only second values\n\tpublic static class SecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getSecond().compareTo(p2.getSecond());\n\t\t}\n\t}\n\n\tpublic static class ReverseSecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getSecond().compareTo(p1.getSecond());\n\t\t}\n\t}\n\n\tpublic static <S, T> Pair<S, T> newPair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\t// Duplicate method to faccilitate backwards compatibility\n\t// - aria42\n\tpublic static <S, T> Pair<S, T> makePair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\tpublic static class LexicographicPairComparator<F, S> implements\n\t\t\tComparator<Pair<F, S>> {\n\t\tComparator<F> firstComparator;\n\t\tComparator<S> secondComparator;\n\n\t\tpublic int compare(Pair<F, S> pair1, Pair<F, S> pair2) {\n\t\t\tint firstCompare = firstComparator.compare(pair1.getFirst(),\n\t\t\t\t\tpair2.getFirst());\n\t\t\tif (firstCompare != 0)\n\t\t\t\treturn firstCompare;\n\t\t\treturn secondComparator.compare(pair1.getSecond(),\n\t\t\t\t\tpair2.getSecond());\n\t\t}\n\n\t\tpublic LexicographicPairComparator(Comparator<F> firstComparator,\n\t\t\t\tComparator<S> secondComparator) {\n\t\t\tthis.firstComparator = firstComparator;\n\t\t\tthis.secondComparator = secondComparator;\n\t\t}\n\t}\n\n\tpublic static class DefaultLexicographicPairComparator<F extends Comparable<F>, S extends Comparable<S>>\n\t\t\timplements Comparator<Pair<F, S>> {\n\n\t\tpublic int compare(Pair<F, S> o1, Pair<F, S> o2) {\n\t\t\tint firstCompare = o1.getFirst().compareTo(o2.getFirst());\n\t\t\tif (firstCompare != 0) {\n\t\t\t\treturn firstCompare;\n\t\t\t}\n\t\t\treturn o2.getSecond().compareTo(o2.getSecond());\n\t\t}\n\n\t}\n\n}" } ]
import java.lang.reflect.Field; import java.lang.reflect.Method; 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 edu.berkeley.nlp.util.CollectionUtils; import edu.berkeley.nlp.util.Factory; import edu.berkeley.nlp.util.LazyIterable; import edu.berkeley.nlp.util.Pair;
6,174
package edu.berkeley.nlp.util.functional; /** * Collection of Functional Utilities you'd find in any functional programming * language. Things like map, filter, reduce, etc.. * * Created by IntelliJ IDEA. User: aria42 Date: Oct 7, 2008 Time: 1:06:08 PM */ public class FunctionalUtils { public static <T> List<T> take(Iterator<T> it, int n) { List<T> result = new ArrayList<T>(); for (int i = 0; i < n && it.hasNext(); ++i) { result.add(it.next()); } return result; } private static Method getMethod(Class c, String field) { Method[] methods = c.getDeclaredMethods(); String trgMethName = "get" + field; Method trgMeth = null; for (Method m : methods) { if (m.getName().equalsIgnoreCase(trgMethName) || m.getName().equalsIgnoreCase(field)) { return m; } } return null; } private static Field getField(Class c, String fieldName) { Field[] fields = c.getDeclaredFields(); for (Field f : fields) { if (f.getName().equalsIgnoreCase(fieldName)) { return f; } } return null; } public static <T> Pair<T, Double> findMax(Iterable<T> xs, Function<T, Double> fn) { double max = Double.NEGATIVE_INFINITY; T argMax = null; for (T x : xs) { double val = fn.apply(x); if (val > max) { max = val; argMax = x; } } return Pair.newPair(argMax, max); } public static <T> Pair<T, Double> findMin(Iterable<T> xs, Function<T, Double> fn) { double min = Double.POSITIVE_INFINITY; T argMin = null; for (T x : xs) { double val = fn.apply(x); if (val < min) { min = val; argMin = x; } } return Pair.newPair(argMin, min); } public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn) { return map(map, fn, (Predicate<K>) Predicates.getTruePredicate(), new HashMap<K, V>()); } public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn, Predicate<K> pred) { return map(map, fn, pred, new HashMap<K, V>()); } public static <C> List make(Factory<C> factory, int k) { List<C> insts = new ArrayList<C>(); for (int i = 0; i < k; i++) { insts.add(factory.newInstance()); } // Fuck you cvs return insts; } public static <K, I, V> Map<K, V> map(Map<K, I> map, Function<I, V> fn, Predicate<K> pred, Map<K, V> resultMap) { for (Map.Entry<K, I> entry : map.entrySet()) { K key = entry.getKey(); I inter = entry.getValue(); if (pred.apply(key)) resultMap.put(key, fn.apply(inter)); } return resultMap; } public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn) { return mapPairs(lst, fn, new HashMap<I, O>()); } public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn, Map<I, O> resultMap) { for (I input : lst) { O output = fn.apply(input); resultMap.put(input, output); } return resultMap; } public static <I, O> List<O> map(Iterable<I> lst, Function<I, O> fn) { return map(lst, fn, (Predicate<O>) Predicates.getTruePredicate()); } public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn) { return lazyMap(lst, fn, (Predicate<O>) Predicates.getTruePredicate()); } public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn, Predicate<O> pred) {
package edu.berkeley.nlp.util.functional; /** * Collection of Functional Utilities you'd find in any functional programming * language. Things like map, filter, reduce, etc.. * * Created by IntelliJ IDEA. User: aria42 Date: Oct 7, 2008 Time: 1:06:08 PM */ public class FunctionalUtils { public static <T> List<T> take(Iterator<T> it, int n) { List<T> result = new ArrayList<T>(); for (int i = 0; i < n && it.hasNext(); ++i) { result.add(it.next()); } return result; } private static Method getMethod(Class c, String field) { Method[] methods = c.getDeclaredMethods(); String trgMethName = "get" + field; Method trgMeth = null; for (Method m : methods) { if (m.getName().equalsIgnoreCase(trgMethName) || m.getName().equalsIgnoreCase(field)) { return m; } } return null; } private static Field getField(Class c, String fieldName) { Field[] fields = c.getDeclaredFields(); for (Field f : fields) { if (f.getName().equalsIgnoreCase(fieldName)) { return f; } } return null; } public static <T> Pair<T, Double> findMax(Iterable<T> xs, Function<T, Double> fn) { double max = Double.NEGATIVE_INFINITY; T argMax = null; for (T x : xs) { double val = fn.apply(x); if (val > max) { max = val; argMax = x; } } return Pair.newPair(argMax, max); } public static <T> Pair<T, Double> findMin(Iterable<T> xs, Function<T, Double> fn) { double min = Double.POSITIVE_INFINITY; T argMin = null; for (T x : xs) { double val = fn.apply(x); if (val < min) { min = val; argMin = x; } } return Pair.newPair(argMin, min); } public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn) { return map(map, fn, (Predicate<K>) Predicates.getTruePredicate(), new HashMap<K, V>()); } public static <K, I, V> Map<K, V> compose(Map<K, I> map, Function<I, V> fn, Predicate<K> pred) { return map(map, fn, pred, new HashMap<K, V>()); } public static <C> List make(Factory<C> factory, int k) { List<C> insts = new ArrayList<C>(); for (int i = 0; i < k; i++) { insts.add(factory.newInstance()); } // Fuck you cvs return insts; } public static <K, I, V> Map<K, V> map(Map<K, I> map, Function<I, V> fn, Predicate<K> pred, Map<K, V> resultMap) { for (Map.Entry<K, I> entry : map.entrySet()) { K key = entry.getKey(); I inter = entry.getValue(); if (pred.apply(key)) resultMap.put(key, fn.apply(inter)); } return resultMap; } public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn) { return mapPairs(lst, fn, new HashMap<I, O>()); } public static <I, O> Map<I, O> mapPairs(Iterable<I> lst, Function<I, O> fn, Map<I, O> resultMap) { for (I input : lst) { O output = fn.apply(input); resultMap.put(input, output); } return resultMap; } public static <I, O> List<O> map(Iterable<I> lst, Function<I, O> fn) { return map(lst, fn, (Predicate<O>) Predicates.getTruePredicate()); } public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn) { return lazyMap(lst, fn, (Predicate<O>) Predicates.getTruePredicate()); } public static <I, O> Iterable<O> lazyMap(Iterable<I> lst, Function<I, O> fn, Predicate<O> pred) {
return new LazyIterable<O, I>(lst, fn, pred, 20);
2
2023-10-22 13:13:22+00:00
8k
UZ9/cs-1331-drivers
src/StartMenuTests.java
[ { "identifier": "TestFailedException", "path": "src/com/cs1331/drivers/exception/TestFailedException.java", "snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}" }, { "identifier": "RecursiveSearch", "path": "src/com/cs1331/drivers/javafx/RecursiveSearch.java", "snippet": "public class RecursiveSearch {\n @SuppressWarnings(\"unchecked\")\n public static <T extends Node> T recursiveSearch(Filter<T> filter, Class<T> type, Pane current) {\n for (int i = 0; i < current.getChildren().size(); i++) {\n Node node = current.getChildren().get(i);\n\n if (type.isAssignableFrom(node.getClass())) {\n T castVar = (T) node;\n\n if (filter.matches(castVar)) {\n return castVar;\n }\n } else if (node instanceof Pane) {\n T res = recursiveSearch(filter, type, (Pane) node);\n if (res != null) return res;\n }\n }\n\n return null;\n }\n}" }, { "identifier": "TestFunction", "path": "src/com/cs1331/drivers/testing/TestFunction.java", "snippet": "public class TestFunction {\n /**\n * Detects if the given Strings do not have the same content (case-sensitive)\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(String actual, String expected) throws TestFailedException {\n boolean failed = false;\n\n if (actual == null) {\n if (expected != null) {\n throw new TestFailedException(\"Test failed! Received null, but expected \\\"\" + expected + \"\\\"\");\n }\n } else if (expected == null) {\n throw new TestFailedException(\"Test failed! Received \\\"\" + actual + \"\\\", but expected null\");\n } else {\n\n if (!actual.replaceAll(\"\\n\", System.lineSeparator()).equals(expected.replaceAll(\"\\n\", System.lineSeparator()))) {\n failed = true;\n }\n }\n\n if (failed) {\n \n \n String expectedString = \"\\\"\" + expected + \"\\\"\";\n String coloredActual = StringUtils.getColorCodedDifference(\"\\\"\" + actual + \"\\\"\", expectedString);\n\n \n if (coloredActual.trim().contains(\"\\n\")) {\n coloredActual = \"\\n\" + coloredActual + \"\\n\";\n }\n if (expected.trim().contains(\"\\n\")) {\n expectedString = \"\\n\\\"\" + expected + \"\\\"\\n\";\n }\n\n throw new TestFailedException(\n \"Strings different! Received \" + coloredActual + \" but expected \" + expectedString);\n }\n }\n\n public static void assertEqual(Iterable<?> actual, Iterable<?> expected) throws TestFailedException {\n\n boolean failed = false;\n\n if (actual == null || expected == null) {\n failed = actual == expected;\n throw new TestFailedException(\n \"List different! Received \\\"\" + actual == null ? \"null\" : TestUtils.iterableToString(actual) + \"\\\", expected \\\"\" + expected == null ? \"null\" : TestUtils.iterableToString(expected) + \"\\\"\");\n } else {\n Iterator<?> aIterator = actual.iterator();\n Iterator<?> eIterator = expected.iterator();\n while (aIterator.hasNext() && eIterator.hasNext()) {\n if (!aIterator.next().equals(eIterator.next())) {\n failed = true;\n }\n }\n\n if (aIterator.hasNext() != eIterator.hasNext()) {\n throw new TestFailedException(\"List lengths different! Received \\\"\" + TestUtils.iterableToString(actual) + \"\\\" but expected \\\"\" + TestUtils.iterableToString(expected) + \"\\\"\");\n }\n }\n\n if (failed) {\n throw new TestFailedException(\n \"List different! Received \\\"\" + TestUtils.iterableToString(actual) + \"\\\", expected \\\"\" + TestUtils.iterableToString(expected) + \"\\\"\");\n }\n\n }\n\n public static void assertEqual(List<String> actual, List<String> expected) throws TestFailedException {\n boolean failed = false;\n\n if (actual == null || expected == null || actual.size() != expected.size()) {\n failed = actual == expected;\n } else {\n for (int i = 0; i < expected.size(); i++) {\n if (expected.get(i) == null) {\n failed = actual.get(i) != null;\n\n } else {\n failed = !actual.get(i).equals(expected.get(i));\n\n }\n if (failed) break;\n }\n }\n\n if (failed) {\n throw new TestFailedException(\n \"List Different! Received \\\"\" + actual + \"\\\", expected \\\"\" + expected + \"\\\"\");\n }\n }\n\n /**\n * Detects if the given integers are not equal.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(int actual, int expected) throws TestFailedException {\n boolean failed = (actual != expected);\n if (failed) {\n throw new TestFailedException(\"Integer value difference: Received \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given doubles are not within 1.0e-6 of one another.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(double actual, double expected) throws TestFailedException {\n final double ALLOWABLE_ERROR = 0.000001;\n\n boolean failed = (Math.abs(actual - expected) > ALLOWABLE_ERROR);\n\n if (failed) {\n throw new TestFailedException(\"Double value difference: \\n\\tReceived \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given booleans do not have equal values.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(boolean actual, boolean expected) throws TestFailedException {\n boolean failed = (actual != expected);\n\n if (failed) {\n throw new TestFailedException(\"Boolean value difference: Received \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given objects are equal by their .equals() methods. By default, this method will also test\n * for symmetry.\n *\n * @param expected Whether or not these two objects should be equal by their .equals() methods\n * @param obj1 The first object to compare.\n * @param obj2 The second object to compare.\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(boolean expected, Object obj1, Object obj2) throws TestFailedException {\n boolean actual = obj1.equals(obj2);\n if (actual != expected) {\n throw new TestFailedException(\"Boolean value difference with .equals() method. When comparing\\n\\\"\" + obj1.toString() + \"\\\" with \\\"\" + obj2.toString() + \"\\\", Received \" + actual + \", expected \" + expected);\n }\n\n if (actual != obj2.equals(obj1)) {\n throw new TestFailedException(\"Asymmetry detected! When comparing \\\"\" + obj1.toString() + \"\\\" with \\\"\" + obj2.toString() + \"\\\", Received \" + actual + \". But when calling .equals() the other way, received \" + !actual);\n }\n }\n\n /**\n * Tests the given code for a particular type of Exception.\n * @param exceptionType The class of the expected Exception.\n * @param codeThatThrowsException Runnable code that is intended to throw an exceptino of type exceptionType. Must NOT throw a TestFailedException\n * @throws TestFailedException\n */\n public static void testForException(Class<? extends Exception> exceptionType, Runnable codeThatThrowsException) throws TestFailedException {\n try {\n codeThatThrowsException.run();\n throw new TestFailedException(exceptionType.getSimpleName() + \" did NOT occur when it was supposed to!\");\n } catch (Exception e) {\n if (e.getClass() == exceptionType) {\n if (e.getMessage() == null || e.getMessage().isBlank()) {\n throw new TestFailedException(\"Make sure you're setting a descriptive message for your \" + e.getClass().getSimpleName() + \"!\");\n }\n // Test passed! Finish running method and return to the invoker\n } else if (e.getClass() == TestFailedException.class && e.getMessage().contains(\"did NOT occur\")) {\n\n throw new TestFailedException(\"No exception occurred! The code should have thrown a \" + exceptionType.getSimpleName());\n\n } else {\n\n throw new TestFailedException(\"Exception class difference! Received \" + e.getClass().getSimpleName() + \" but expected \" + exceptionType.getSimpleName() + \".\"\n + \"\\nFull stack trace:\\n\" + StringUtils.stackTraceToString(e));\n\n }\n }\n }\n\n /**\n * Tester for String inputs. Takes in a String -> String function, and compares the output with the desired output.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @param inputs The StringInput values to test.\n * @throws TestFailedException\n */\n public static void testStringInputs(String actual, TestUtils.StringFunction codeToRun, TestUtils.StringInput[] inputs) throws TestFailedException {\n\n for (TestUtils.StringInput stringInput : inputs) {\n try {\n assertEqual(actual, codeToRun.run(stringInput.getStringValue()));\n } catch (TestFailedException tfe) {\n throw new TestFailedException(\"When inputted string is \" + stringInput.toString() + \": \" + tfe.getMessage());\n }\n }\n\n }\n\n /**\n * Convenience method that calls testStringInputs(String, StringFunction, StringInput[]) for ALL\n * values of the StringFunction enum.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @throws TestFailedException\n */\n public static void testStringInputs(String actual, TestUtils.StringFunction codeToRun) throws TestFailedException {\n testStringInputs(actual, codeToRun, TestUtils.StringInput.values());\n }\n\n /**\n * Tester for String inputs. Takes in a String -> String function, and compares the output with the desired output.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @param inputs The StringInput values to test.\n * @throws TestFailedException\n */\n public static void testStringInputsForException(Class<? extends Exception> exceptionType, Consumer<String> codeToRun, TestUtils.StringInput... inputs) throws TestFailedException {\n\n for (TestUtils.StringInput stringInput : inputs) {\n try {\n testForException(exceptionType, () -> codeToRun.accept(stringInput.getStringValue()));\n } catch (TestFailedException tfe) {\n throw new TestFailedException(\"When inputted string is \" + stringInput.toString() + \": \" + tfe.getMessage());\n }\n }\n\n }\n\n /**\n * Convenience method that calls testStringInputs(String, StringFunction, StringInput[]) for ALL\n * values of the StringFunction enum.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @throws TestFailedException\n */\n public static void testStringInputsForException(Class<? extends Exception> exceptionType, Consumer<String> codeToRun) throws TestFailedException {\n testStringInputsForException(exceptionType, codeToRun, TestUtils.StringInput.values());\n }\n\n /**\n * Prints an error message\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException If the test fails\n */\n public static void failTest(String errorMessage) throws TestFailedException {\n throw new TestFailedException(\"An error occurred: \" + errorMessage);\n }\n\n}" }, { "identifier": "TestManager", "path": "src/com/cs1331/drivers/testing/TestManager.java", "snippet": "public class TestManager {\n protected volatile static AtomicInteger classTests = new AtomicInteger();\n protected volatile static AtomicInteger classTestsFailed = new AtomicInteger();\n\n private static List<String> filter;\n\n /**\n * A list of the currently registered classes to test\n */\n private static final List<Class<?>> testClazzes = new ArrayList<>();\n\n /**\n * A list of the currently registered data classes\n */\n private static final List<Class<?>> dataClazzes = new ArrayList<>();\n\n /**\n * When this method is called, the TestManager will run all tests in the given\n * classes.\n * \n * @param classes The classes to test.\n */\n public static void runTestsOn(Stage stage, Class<?>... classes) {\n for (Class<?> currentClass : classes) {\n registerClass(currentClass);\n }\n\n executeNextTest(stage);\n }\n\n public static void registerDataClasses(Class<?>... classes) {\n for (Class<?> clazz : classes) {\n registerDataClass(clazz);\n }\n }\n\n private static int currentTestChain = 0;\n\n /**\n * Registers and marks test class to be scanned during test execution.\n * \n * @param clazz The input class\n */\n public static void registerClass(Class<?> clazz) {\n if (filter == null || filter.isEmpty() || filter.stream().anyMatch(s -> s.equals(clazz.getName()))) {\n testClazzes.add(clazz);\n }\n }\n\n public static void registerDataClass(Class<?> clazz) {\n dataClazzes.add(clazz);\n }\n\n public static void startNextTestSuite() {\n\n }\n\n /**\n * Executes all registered tests.\n */\n public static void executeNextTest(Stage stage) {\n injectData(stage);\n\n ExecutorService executor = Executors.newFixedThreadPool(1);\n\n List<Runnable> runnables = new ArrayList<>();\n\n runnables.add(new TestContainer(testClazzes.get(currentTestChain)));\n\n // for (Class<?> testClass : testClazzes) {\n // runnables.add(new TestContainer(testClass));\n // }\n\n for (Runnable r : runnables) {\n Future<?> future = executor.submit(r);\n\n try {\n future.get(10, TimeUnit.SECONDS);\n } catch (InterruptedException ignored) {\n\n } catch (ExecutionException e) {\n e.getCause().printStackTrace();\n } catch (TimeoutException e) {\n future.cancel(true);\n\n System.out.println(ColorUtils.formatColorString(AsciiColorCode.BRIGHT_RED_BACKGROUND,\n AsciiColorCode.BRIGHT_WHITE_FOREGROUND, \" FAILED \\u00BB \")\n + \" A test failed by exceeding the time limit. You likely have an infinite loop somewhere.\");\n\n System.exit(-1);\n }\n\n }\n\n executor.shutdown();\n\n StringUtils.printHorizontalLine();\n\n StringUtils.printTextCentered(\"Test Results\");\n System.out.println();\n StringUtils.printTextCentered(\n String.format(\"TOTAL TESTS PASSED: %d/%d\", classTests.get() - classTestsFailed.get(),\n classTests.get()));\n StringUtils.printHorizontalLine();\n\n currentTestChain++;\n\n }\n\n private static void injectData(Stage stage) {\n\n for (Class<?> dataClass : dataClazzes) {\n for (Field f : dataClass.getFields()) {\n InjectData injectAnnotation = f.getAnnotation(InjectData.class);\n\n if (injectAnnotation != null) {\n Scanner scanner = null;\n\n StringBuilder output = new StringBuilder();\n\n if (injectAnnotation.name().equals(\"stage\")) {\n f.setAccessible(true);\n\n try {\n f.set(null, stage);\n } catch (Exception e) {\n e.printStackTrace();\n }\n \n return;\n } else {\n try {\n scanner = new Scanner(new File(injectAnnotation.name()));\n\n while (scanner.hasNextLine()) {\n output.append(scanner.nextLine()).append(\"\\n\");\n }\n } catch (FileNotFoundException e) {\n System.out.println(\"COULDN'T FIND INJECT DATA FILE \" + injectAnnotation.name());\n System.exit(-1);\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n }\n\n // Inject data into variable\n f.setAccessible(true);\n\n try {\n // Set private static final\n f.set(null, output.toString());\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(-1);\n }\n\n }\n }\n }\n }\n\n /**\n * Prints a formatted test category section\n * \n * @param category The name of the section (most likely the class name)\n */\n protected static void printTestCategory(String category) {\n StringUtils.printHorizontalLine();\n StringUtils.printTextCentered(category);\n System.out.println();\n }\n\n /**\n * Sets a filter to determine what test class files can be run.\n * This is primarily used in the CLI options.\n * \n * @param filter The filter of classes\n */\n public static void setTestFilter(List<String> filter) {\n TestManager.filter = filter;\n }\n}" } ]
import java.io.File; import com.cs1331.drivers.annotations.AfterTest; import com.cs1331.drivers.annotations.InjectData; import com.cs1331.drivers.annotations.TestCase; import com.cs1331.drivers.annotations.Tip; import com.cs1331.drivers.exception.TestFailedException; import com.cs1331.drivers.javafx.RecursiveSearch; import com.cs1331.drivers.testing.TestFunction; import com.cs1331.drivers.testing.TestManager; import javafx.application.Platform; import javafx.event.Event; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.Pane; import javafx.stage.Stage;
4,900
public class StartMenuTests { @TestCase(name = "valid title property") @Tip(description = "Make sure you're setting your stage title correctly!") public void checkApplicationTitle() throws TestFailedException { TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship"); } @TestCase(name = "battleshipImage.jpg exists") @Tip(description = "Make sure you have battleshipImage.jpg (NOT png) in the same directory as your files!") public void checkBattleshipImage() throws TestFailedException { File file = new File("battleshipImage.jpg"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "enemy.txt exists") @Tip(description = "Make sure you have enemy.txt in the same directory as your files!") public void checkEnemyTxt() throws TestFailedException { File file = new File("enemy.txt"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "player.txt exists") @Tip(description = "Make sure you have player.txt in the same directory as your files!") public void checkPlayerTxt() throws TestFailedException { File file = new File("player.txt"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "Start menu contains a button with text \"Start Game!\"") @Tip(description = "Make sure your button formatting is correct!") public void checkForButton() throws TestFailedException { Scene scene = StageData.stage.getScene(); Button returned = RecursiveSearch.recursiveSearch( ((Button b) -> b.getText().equals("Start Game!")), Button.class, (Pane) scene.getRoot()); TestFunction.assertEqual(true, returned != null); } @TestCase(name = "Start menu contains a label somewhere with \"Battleship\"") @Tip(description = "Make sure your button formatting is correct!") public void checkForBattleshipLabel() throws TestFailedException { Scene scene = StageData.stage.getScene(); Label returned = RecursiveSearch.recursiveSearch( ((Label b) -> b.getText().equals("Battleship")), Label.class, (Pane) scene.getRoot()); TestFunction.assertEqual(true, returned != null); } @AfterTest public void afterTest() { Scene scene = StageData.stage.getScene(); Button returned = RecursiveSearch.recursiveSearch( ((Button b) -> b.getText().equals("Start Game!")), Button.class, (Pane) scene.getRoot()); if (returned != null) { Platform.runLater(() -> { returned.fire(); System.out.println("set scene"); StageData.currentScene = returned.getScene();
public class StartMenuTests { @TestCase(name = "valid title property") @Tip(description = "Make sure you're setting your stage title correctly!") public void checkApplicationTitle() throws TestFailedException { TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship"); } @TestCase(name = "battleshipImage.jpg exists") @Tip(description = "Make sure you have battleshipImage.jpg (NOT png) in the same directory as your files!") public void checkBattleshipImage() throws TestFailedException { File file = new File("battleshipImage.jpg"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "enemy.txt exists") @Tip(description = "Make sure you have enemy.txt in the same directory as your files!") public void checkEnemyTxt() throws TestFailedException { File file = new File("enemy.txt"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "player.txt exists") @Tip(description = "Make sure you have player.txt in the same directory as your files!") public void checkPlayerTxt() throws TestFailedException { File file = new File("player.txt"); TestFunction.assertEqual(file.exists(), true); } @TestCase(name = "Start menu contains a button with text \"Start Game!\"") @Tip(description = "Make sure your button formatting is correct!") public void checkForButton() throws TestFailedException { Scene scene = StageData.stage.getScene(); Button returned = RecursiveSearch.recursiveSearch( ((Button b) -> b.getText().equals("Start Game!")), Button.class, (Pane) scene.getRoot()); TestFunction.assertEqual(true, returned != null); } @TestCase(name = "Start menu contains a label somewhere with \"Battleship\"") @Tip(description = "Make sure your button formatting is correct!") public void checkForBattleshipLabel() throws TestFailedException { Scene scene = StageData.stage.getScene(); Label returned = RecursiveSearch.recursiveSearch( ((Label b) -> b.getText().equals("Battleship")), Label.class, (Pane) scene.getRoot()); TestFunction.assertEqual(true, returned != null); } @AfterTest public void afterTest() { Scene scene = StageData.stage.getScene(); Button returned = RecursiveSearch.recursiveSearch( ((Button b) -> b.getText().equals("Start Game!")), Button.class, (Pane) scene.getRoot()); if (returned != null) { Platform.runLater(() -> { returned.fire(); System.out.println("set scene"); StageData.currentScene = returned.getScene();
TestManager.executeNextTest(StageData.stage);
3
2023-10-20 03:06:59+00:00
8k
AkramLZ/ServerSync
serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServerSyncPlugin.java
[ { "identifier": "ServerSync", "path": "serversync-common/src/main/java/me/akraml/serversync/ServerSync.java", "snippet": "@Getter\npublic class ServerSync {\n\n private static ServerSync INSTANCE;\n\n private final ServersManager serversManager;\n private final MessageBrokerService messageBrokerService;\n\n /**\n * Private constructor to prevent instantiation from outside and enforce the singleton pattern.\n *\n * @param serversManager The servers manager to manage server operations.\n * @param messageBrokerService The message broker service to handle messaging.\n */\n private ServerSync(final ServersManager serversManager,\n final MessageBrokerService messageBrokerService) {\n this.serversManager = serversManager;\n this.messageBrokerService = messageBrokerService;\n }\n\n /**\n * Retrieves the singleton instance of ServerSync.\n *\n * @return The singleton instance of ServerSync.\n */\n public static ServerSync getInstance() {\n return INSTANCE;\n }\n\n /**\n * Initializes the singleton instance of ServerSync. If the instance is already\n * initialized, this method will throw a {@link RuntimeException} to prevent\n * re-initialization.\n *\n * @param serversManager The servers manager for server operations.\n * @param messageBrokerService The message broker service for messaging.\n * @throws RuntimeException if an instance is already initialized.\n */\n public static void initializeInstance(final ServersManager serversManager,\n final MessageBrokerService messageBrokerService) {\n if (INSTANCE != null) throw new RuntimeException(\"Instance is already initialized\");\n INSTANCE = new ServerSync(serversManager, messageBrokerService);\n }\n\n}" }, { "identifier": "RedisMessageBrokerService", "path": "serversync-common/src/main/java/me/akraml/serversync/broker/RedisMessageBrokerService.java", "snippet": "public final class RedisMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<JedisPool> {\n\n private final Gson gson = new Gson();\n private final ConnectionCredentials credentials;\n private JedisPool pool;\n\n /**\n * Constructs a new RedisMessageBroker with the given {@link ServersManager} and {@link ConnectionCredentials}.\n *\n * @param serversManager The servers manager to use for actions on servers.\n * @param credentials The credentials used to establish a connection with Redis.\n */\n public RedisMessageBrokerService(final ServersManager serversManager,\n final ConnectionCredentials credentials) {\n super(serversManager);\n this.credentials = credentials;\n }\n\n @Override\n public ConnectionResult connect() {\n\n // Initializes a jedis pool configuration with required information.\n final JedisPoolConfig poolConfig = new JedisPoolConfig();\n poolConfig.setMaxTotal(credentials.getProperty(RedisCredentialsKeys.MAX_TOTAL, Integer.class));\n poolConfig.setMaxIdle(credentials.getProperty(RedisCredentialsKeys.MAX_IDLE, Integer.class));\n poolConfig.setMinIdle(credentials.getProperty(RedisCredentialsKeys.MIN_IDLE, Integer.class));\n poolConfig.setBlockWhenExhausted(credentials.getProperty(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, Boolean.class));\n poolConfig.setMinEvictableIdleTime(\n Duration.ofMillis(credentials.getProperty(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, Long.class))\n );\n poolConfig.setTimeBetweenEvictionRuns(\n Duration.ofMillis(credentials.getProperty(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, Long.class))\n );\n\n // Initializes a new jedis pool instance to hold connections on.\n this.pool = new JedisPool(\n poolConfig,\n credentials.getProperty(RedisCredentialsKeys.HOST, String.class),\n credentials.getProperty(RedisCredentialsKeys.PORT, Integer.class),\n credentials.getProperty(RedisCredentialsKeys.TIMEOUT, Integer.class),\n credentials.getProperty(RedisCredentialsKeys.PASSWORD, String.class)\n );\n\n // Tests if the connection works properly and return the result.\n try (final Jedis ignore = pool.getResource()) {\n return ConnectionResult.SUCCESS;\n } catch (final Exception exception) {\n return ConnectionResult.FAILURE;\n }\n }\n\n @Override\n public JedisPool getConnection() {\n return pool;\n }\n\n @Override\n public ConnectionCredentials getCredentials() {\n return credentials;\n }\n\n @Override\n public void startHandler() {\n CompletableFuture.runAsync(() -> {\n try (final Jedis jedis = getConnection().getResource()) {\n jedis.subscribe(new JedisPubSub() {\n @Override\n public void onMessage(String channel, String message) {\n onMessageReceive(gson.fromJson(message, JsonObject.class));\n }\n }, \"serversync:servers\");\n }\n }).exceptionally(throwable -> {\n throwable.printStackTrace(System.err);\n return null;\n });\n }\n\n @Override\n public void stop() {\n close();\n }\n\n @Override\n public void publish(JsonObject message) {\n try(final Jedis jedis = pool.getResource()) {\n jedis.publish(\"serversync:servers\", message.toString());\n }\n }\n}" }, { "identifier": "ConnectionResult", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionResult.java", "snippet": "public enum ConnectionResult {\n\n /**\n * Indicates a successful connection.\n */\n SUCCESS,\n\n /**\n * Indicates a failed connection.\n */\n FAILURE\n\n}" }, { "identifier": "ConnectionType", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionType.java", "snippet": "public enum ConnectionType {\n\n REDIS,\n RABBITMQ\n\n}" }, { "identifier": "ConnectionCredentials", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/ConnectionCredentials.java", "snippet": "public final class ConnectionCredentials {\n\n private final Map<CredentialsKey, Object> keyMap = new HashMap<>();\n\n /**\n * Constructor must be private to disallow external initialization.\n */\n private ConnectionCredentials() {\n }\n\n /**\n * Retrieves the value associated with the specified key and casts it to the specified type.\n *\n * @param key The key of the property.\n * @param typeClass The class representing the type of the property.\n * @param <T> The type of the property.\n * @return The value associated with the key, cast to the specified type.\n * @throws ConnectionAuthenticationException if the key is missing in the credentials.\n * @throws ClassCastException if the type is not the same as the key.\n */\n public <T> T getProperty(final CredentialsKey key,\n final Class<T> typeClass) {\n if (!keyMap.containsKey(key)) {\n throw new ConnectionAuthenticationException(\"Missing key=\" + key);\n }\n Object keyObject = keyMap.get(key);\n return typeClass.cast(keyObject);\n }\n\n /**\n * Creates a new instance of the ConnectionCredentials.Builder.\n *\n * @return A new instance of the ConnectionCredentials.Builder.\n */\n public static Builder newBuilder() {\n return new Builder();\n }\n\n /**\n * A builder class for constructing ConnectionCredentials objects.\n */\n public static final class Builder {\n\n private final ConnectionCredentials credentials;\n\n private Builder() {\n this.credentials = new ConnectionCredentials();\n }\n\n /**\n * Adds a key-value pair to the connection credentials.\n *\n * @param key The key of the credential.\n * @param value The value of the credential.\n * @return The Builder instance.\n */\n public Builder addKey(final CredentialsKey key,\n final Object value) {\n credentials.keyMap.put(key, value);\n return this;\n }\n\n /**\n * Builds and returns the ConnectionCredentials object.\n *\n * @return The constructed ConnectionCredentials object.\n */\n public ConnectionCredentials build() {\n return credentials;\n }\n\n }\n\n}" }, { "identifier": "RedisCredentialsKeys", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/credentials/RedisCredentialsKeys.java", "snippet": "public enum RedisCredentialsKeys implements CredentialsKey {\n\n HOST(\"host\"),\n PORT(\"port\"),\n PASSWORD(\"password\"),\n TIMEOUT(\"timeout\"),\n MAX_TOTAL(\"maxTotal\"),\n MAX_IDLE(\"maxIdle\"),\n MIN_IDLE(\"minIdle\"),\n MIN_EVICTABLE_IDLE_TIME(\"minEvictableIdleTime\"),\n TIME_BETWEEN_EVICTION_RUNS(\"timeBetweenEvictionRuns\"),\n BLOCK_WHEN_EXHAUSTED(\"blockWhenExhausted\");\n\n private final String keyName;\n\n RedisCredentialsKeys(String keyName) {\n this.keyName = keyName;\n }\n\n @Override\n public String getKeyName() {\n return keyName;\n }\n}" }, { "identifier": "ServersManager", "path": "serversync-common/src/main/java/me/akraml/serversync/server/ServersManager.java", "snippet": "public abstract class ServersManager {\n\n /** Timer to schedule and manage the heartbeat task. */\n private final Timer timer = new Timer();\n\n /** Map storing the servers using their names as the key. */\n private final Map<String, ServerImpl> servers = new HashMap<>();\n\n /** Integers for heartbeat task delay and maximum time to remove the server. */\n protected int heartbeatSchedulerDelay, maxAliveTime;\n\n /**\n * Starts a recurring task to check servers for their heartbeat signal.\n * Servers that haven't sent a heartbeat signal within the last 30 seconds will be removed.\n */\n public final void startHeartbeatTask() {\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n final List<ServerImpl> toRemove = new ArrayList<>();\n servers.values().forEach(server -> {\n if (System.currentTimeMillis() - server.getLastHeartbeat() > maxAliveTime) {\n toRemove.add(server);\n }\n });\n toRemove.forEach(ServersManager.this::removeServer);\n toRemove.clear();\n }\n }, 0L, Duration.ofSeconds(heartbeatSchedulerDelay).toMillis());\n }\n\n /**\n * Retrieves a server instance by its name.\n *\n * @param name The name of the server.\n * @return The server instance or null if not found.\n */\n public final Server getServer(String name) {\n return this.servers.get(name);\n }\n\n /**\n * Adds a server to the managed collection of servers.\n *\n * @param server The server to be added.\n */\n public final void addServer(Server server) {\n this.servers.put(server.getName(), (ServerImpl) server);\n registerInProxy(server);\n }\n\n /**\n * Removes a server from the managed collection of servers.\n * Also, triggers an unregister action specific to the proxy.\n *\n * @param server The server to be removed.\n */\n public final void removeServer(Server server) {\n unregisterFromProxy(server);\n this.servers.remove(server.getName());\n }\n\n /**\n * Abstract method that should be implemented to unregister a server from the associated proxy.\n *\n * @param server The server to be unregistered from the proxy.\n */\n protected abstract void unregisterFromProxy(Server server);\n\n /**\n * Abstract method that should be implemented to register a server in the proxy server.\n *\n * @param server The server to be registered in the proxy.\n */\n protected abstract void registerInProxy(Server server);\n}" } ]
import me.akraml.serversync.connection.auth.ConnectionCredentials; import me.akraml.serversync.connection.auth.credentials.RedisCredentialsKeys; import me.akraml.serversync.server.ServersManager; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import lombok.Getter; import me.akraml.serversync.ServerSync; import me.akraml.serversync.VersionInfo; import me.akraml.serversync.broker.RedisMessageBrokerService; import me.akraml.serversync.connection.ConnectionResult; import me.akraml.serversync.connection.ConnectionType;
3,709
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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 me.akraml.serversync.bungee; /** * An implementation for ServerSync in BungeeCord platform. */ @Getter public final class BungeeServerSyncPlugin extends Plugin { private Configuration config; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onLoad() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } try { loadConfig(); } catch (Exception exception) { exception.printStackTrace(System.err); } } @Override public void onEnable() { final long start = System.currentTimeMillis(); getLogger().info("\n" + " __ __ \n" + "/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" + "\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" + "_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" + "\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" + " |___/ \n"); getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL."); final ServersManager serversManager = new BungeeServersManager(this); // Initialize message broker service. final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service")); switch (connectionType) { case REDIS: { getLogger().info("ServerSync will run under Redis message broker..."); long redisStartTime = System.currentTimeMillis(); final Configuration redisSection = config.getSection("redis"); final ConnectionCredentials credentials = ConnectionCredentials.newBuilder() .addKey(RedisCredentialsKeys.HOST, redisSection.getString("host")) .addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port")) .addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password")) .addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout")) .addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total")) .addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle")) .addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle")) .addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time")) .addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs")) .addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted")) .build(); final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService( serversManager, credentials );
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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 me.akraml.serversync.bungee; /** * An implementation for ServerSync in BungeeCord platform. */ @Getter public final class BungeeServerSyncPlugin extends Plugin { private Configuration config; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onLoad() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } try { loadConfig(); } catch (Exception exception) { exception.printStackTrace(System.err); } } @Override public void onEnable() { final long start = System.currentTimeMillis(); getLogger().info("\n" + " __ __ \n" + "/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" + "\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" + "_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" + "\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" + " |___/ \n"); getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL."); final ServersManager serversManager = new BungeeServersManager(this); // Initialize message broker service. final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service")); switch (connectionType) { case REDIS: { getLogger().info("ServerSync will run under Redis message broker..."); long redisStartTime = System.currentTimeMillis(); final Configuration redisSection = config.getSection("redis"); final ConnectionCredentials credentials = ConnectionCredentials.newBuilder() .addKey(RedisCredentialsKeys.HOST, redisSection.getString("host")) .addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port")) .addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password")) .addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout")) .addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total")) .addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle")) .addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle")) .addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time")) .addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs")) .addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted")) .build(); final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService( serversManager, credentials );
final ConnectionResult connectionResult = messageBrokerService.connect();
2
2023-10-21 12:47:58+00:00
8k
neftalito/R-Info-Plus
form/Robot.java
[ { "identifier": "Variable", "path": "arbol/Variable.java", "snippet": "public class Variable extends Expresion {\n private String value;\n private boolean editable;\n Robot rob;\n RobotAST r;\n private String nombreTipoRobot;\n DeclaracionRobots dr;\n\n public Variable(final Identificador I, final Tipo T, final DeclaracionVariable var, final DeclaracionRobots robAST,\n final String nombreTipoRobot) throws Exception {\n synchronized (this) {\n this.dr = robAST;\n this.DV = var;\n this.setI(I);\n this.value = \"Undefined\";\n if (T == null) {\n if (var.EstaVariable(I.toString())) {\n final Variable tmp = var.findByName(I.toString());\n this.setT(tmp.getT());\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n }\n } else {\n this.setT(T);\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n if (this.getT().tipo == 66) {\n this.r = robAST.getRobot(nombreTipoRobot);\n }\n }\n }\n }\n\n public RobotAST getR() {\n return this.r;\n }\n\n @Override\n public String getValue(final DeclaracionVariable var) throws Exception {\n String res = \"undefineD\";\n if (var.EstaParametro(this.I.toString())) {\n final Variable tmp = var.findByName(this.I.toString());\n res = tmp.getValor();\n return res;\n }\n this.reportError(\"Variable \" + this.getI().toString() + \" no declarada\");\n throw new Exception(\"Variable \" + this.getI().toString() + \" no declarada\");\n }\n\n public String getValor() {\n return this.value;\n }\n\n public void setValue(final String str) {\n this.value = str;\n }\n\n public boolean esEditable() {\n return this.editable;\n }\n\n public void setEditable(final boolean bool) {\n this.editable = bool;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public boolean isCompatible(final Variable tmp) {\n switch (tmp.getT().getTipo()) {\n case 19:\n case 23: {\n return this.getT().getTipo() == 23 || this.getT().getTipo() == 19;\n }\n case 20:\n case 32:\n case 33: {\n return this.getT().getTipo() == 20 || this.getT().getTipo() == 32 || this.getT().getTipo() == 33;\n }\n default: {\n return false;\n }\n }\n }\n\n public void setTipoRobot(final String nombreTipoRobot) {\n this.nombreTipoRobot = nombreTipoRobot;\n }\n\n public String getTipoRobot() {\n return this.nombreTipoRobot;\n }\n\n @Override\n public Object clone() {\n synchronized (this) {\n Variable obj = null;\n try {\n obj = new Variable(this.I, this.T, this.DV, this.dr, null);\n obj.setValue(this.getValor());\n } catch (Exception ex) {\n System.out.println(\"error en el clone de Variable!\");\n Logger.getLogger(Variable.class.getName()).log(Level.SEVERE, null, ex);\n }\n return obj;\n }\n }\n}" }, { "identifier": "Sentencia", "path": "arbol/sentencia/Sentencia.java", "snippet": "public abstract class Sentencia extends AST {\n DeclaracionVariable varAST;\n Robot r;\n\n public Robot getRobot() {\n return this.r;\n }\n\n public void setRobot(final Robot r) {\n this.r = r;\n }\n\n public void ejecutar() throws Exception {\n }\n\n public void setDV(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public DeclaracionVariable getDV() {\n return this.varAST;\n }\n\n @Override\n public void setPrograma(final Programa P) {\n this.programa = P;\n }\n\n @Override\n public Programa getPrograma() {\n return this.programa;\n }\n}" }, { "identifier": "ParametroFormal", "path": "arbol/ParametroFormal.java", "snippet": "public class ParametroFormal extends AST {\n Identificador I;\n Tipo T;\n String TA;\n public String value;\n\n public Identificador getI() {\n return this.I;\n }\n\n public void setI(final Identificador I) {\n this.I = I;\n }\n\n public Tipo getT() {\n return this.T;\n }\n\n public void setT(final Tipo T) {\n this.T = T;\n }\n\n public String getTA() {\n return this.TA;\n }\n\n public void setTA(final String TA) {\n this.TA = TA;\n }\n\n public String getValue() {\n return this.value;\n }\n\n public void setValue(final String value) {\n this.value = value;\n }\n\n public ParametroFormal(final Identificador I, final Tipo T, final String TA) {\n this.I = I;\n this.T = T;\n this.TA = TA;\n }\n}" }, { "identifier": "Proceso", "path": "arbol/Proceso.java", "snippet": "public class Proceso extends AST {\n Identificador I;\n ArrayList<ParametroFormal> PF;\n DeclaracionProcesos DP;\n DeclaracionVariable DV;\n Cuerpo C;\n\n public Proceso(final Identificador I, final ArrayList<ParametroFormal> PF, final DeclaracionProcesos DP,\n final DeclaracionVariable DV, final Cuerpo C) {\n this.I = I;\n this.PF = PF;\n this.DP = DP;\n this.DV = DV;\n this.C = C;\n }\n\n public Cuerpo getC() {\n return this.C;\n }\n\n public void setC(final Cuerpo C) {\n this.C = C;\n }\n\n public DeclaracionProcesos getDP() {\n return this.DP;\n }\n\n public void setDP(final DeclaracionProcesos DP) {\n this.DP = DP;\n }\n\n public DeclaracionVariable getDV() {\n return this.DV;\n }\n\n public void setDV(final DeclaracionVariable DV) {\n this.DV = DV;\n }\n\n public Identificador getI() {\n return this.I;\n }\n\n public void setI(final Identificador I) {\n this.I = I;\n }\n\n public ArrayList<ParametroFormal> getPF() {\n return this.PF;\n }\n\n public void setPF(final ArrayList<ParametroFormal> PF) {\n this.PF = PF;\n }\n}" }, { "identifier": "Identificador", "path": "arbol/Identificador.java", "snippet": "public class Identificador extends AST {\n String spelling;\n\n public Identificador(final String spelling) {\n this.spelling = spelling;\n }\n\n public boolean equals(final String str) {\n return this.spelling.equals(str);\n }\n\n @Override\n public String toString() {\n return this.spelling;\n }\n}" }, { "identifier": "Mover", "path": "arbol/sentencia/primitiva/Mover.java", "snippet": "public class Mover extends Primitiva {\n int ciclo;\n\n public Mover() {\n this.ciclo = 1;\n }\n\n public int getCiclo() {\n return this.ciclo;\n }\n\n @Override\n public void ejecutar() throws Exception {\n this.programa.getCity().setOk(false);\n this.getRobot().mover();\n }\n\n @Override\n public Object clone() throws CloneNotSupportedException {\n return new Mover();\n }\n}" }, { "identifier": "DeclaracionVariable", "path": "arbol/DeclaracionVariable.java", "snippet": "public class DeclaracionVariable extends AST {\n public ArrayList<Variable> variables;\n\n public DeclaracionVariable(final ArrayList<Variable> var) {\n this.variables = var;\n }\n\n public void imprimir() {\n for (final Variable variable : this.variables) {\n System.out.println(variable.getI().toString());\n }\n }\n\n public boolean EstaParametro(final String act) throws Exception {\n int i;\n for (i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n if (i == this.variables.size()) {\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n return false;\n }\n\n public boolean EstaVariable(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public Variable findByName(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().toString().equals(act)) {\n return this.variables.get(i);\n }\n }\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n}" }, { "identifier": "Cuerpo", "path": "arbol/Cuerpo.java", "snippet": "public class Cuerpo extends AST {\n private ArrayList<Sentencia> S;\n DeclaracionVariable varAST;\n Robot rob;\n\n public Cuerpo(final ArrayList<Sentencia> S, final DeclaracionVariable varAST) {\n this.setS(S);\n this.varAST = varAST;\n }\n\n public void ejecutar() throws Exception {\n for (final Sentencia single : this.S) {\n single.setDV(this.varAST);\n single.ejecutar();\n }\n }\n\n public Robot getRobot() {\n return this.rob;\n }\n\n public void setRobot(final Robot rob) {\n this.rob = rob;\n for (final Sentencia single : this.S) {\n single.setRobot(this.rob);\n }\n }\n\n public ArrayList<Sentencia> getS() {\n return this.S;\n }\n\n public void setS(final ArrayList<Sentencia> S) {\n this.S = S;\n }\n\n @Override\n public void setPrograma(final Programa P) {\n this.programa = P;\n for (final Sentencia single : this.S) {\n single.setPrograma(P);\n }\n }\n\n public void setDV(final DeclaracionVariable DV) {\n for (final Sentencia single : this.S) {\n single.setDV(DV);\n }\n }\n}" }, { "identifier": "DeclaracionProcesos", "path": "arbol/DeclaracionProcesos.java", "snippet": "public class DeclaracionProcesos extends AST {\n public ArrayList<Proceso> procesos;\n\n public ArrayList<Proceso> getProcesos() {\n return this.procesos;\n }\n\n public void setProcesos(final ArrayList<Proceso> procesos) {\n this.procesos = procesos;\n }\n\n public DeclaracionProcesos(final ArrayList<Proceso> procesos) {\n this.procesos = procesos;\n }\n\n public boolean estaProceso(final String spelling) {\n for (int i = 0; i < this.procesos.size(); ++i) {\n if (this.procesos.get(i).I.spelling.equals(spelling)) {\n return true;\n }\n }\n return false;\n }\n\n public Proceso getProceso(final String spelling) {\n final Proceso proc = null;\n for (int i = 0; i < this.procesos.size(); ++i) {\n if (this.procesos.get(i).I.spelling.equals(spelling)) {\n return this.procesos.get(i);\n }\n }\n return proc;\n }\n}" } ]
import arbol.Variable; import arbol.sentencia.Sentencia; import arbol.ParametroFormal; import arbol.Proceso; import java.beans.PropertyChangeListener; import java.awt.Image; import arbol.Identificador; import java.io.IOException; import java.net.UnknownHostException; import java.io.DataOutputStream; import java.net.Socket; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import arbol.sentencia.primitiva.Mover; import java.io.FileReader; import java.io.File; import java.awt.Color; import java.beans.PropertyChangeSupport; import javax.swing.ImageIcon; import arbol.DeclaracionVariable; import arbol.Cuerpo; import arbol.DeclaracionProcesos; import java.util.ArrayList;
5,558
this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); return; } this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo"); throw new Exception("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo"); } public ArrayList<Coord> getRuta() { return this.ruta; } public Ciudad getCity() { return this.city; } public void tomarFlor() throws Exception { if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) { this.setFlores(this.getFlores() + 1); this.esperarRefresco.esperar(this.id); return; } this.setFlores(this.getFlores()); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"tomarFlor\" debido a que no hay ninguna flor en la esquina"); } public int getFlores() { return this.floresEnBolsa; } public void setFlores(final int flores) { final int old = this.getFlores(); this.floresEnBolsa = flores; this.pcs.firePropertyChange("flores", old, flores); } public void tomarPapel() throws Exception { if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) { this.setPapeles(this.getPapeles() + 1); this.esperarRefresco.esperar(this.id); return; } this.setPapeles(this.getPapeles()); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"tomarPapel\" debido a que no hay ningun papel en la esquina"); } public boolean HayPapelEnLaBolsa() { return this.getPapeles() > 0; } public boolean HayFlorEnLaBolsa() { return this.getFlores() > 0; } public int getPapeles() { return this.papelesEnBolsa; } public void setColor(final Color col) { final Color old = this.color; this.color = col; this.pcs.firePropertyChange("color", old, col); } public Color getColor() { return this.color; } public void setPapeles(final int papeles) { final int old = this.getPapeles(); this.papelesEnBolsa = papeles; this.pcs.firePropertyChange("papeles", old, papeles); } public void depositarPapel() throws Exception { if (this.getPapeles() > 0) { this.setPapeles(this.getPapeles() - 1); this.getCity().dejarPapel(this.PosAv(), this.PosCa()); this.esperarRefresco.esperar(this.id); return; } this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa"); } public void depositarFlor() throws Exception { if (this.getFlores() > 0) { this.setFlores(this.getFlores() - 1); this.getCity().dejarFlor(this.PosAv(), this.PosCa()); this.esperarRefresco.esperar(this.id); return; } this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores"); } public ArrayList<ArrayList<Coord>> getRutas() { return this.rutas; } public void setRuta(final ArrayList<Coord> ruta) { this.ruta = ruta; } public void setRutas(final ArrayList<ArrayList<Coord>> rutas) { this.rutas = rutas; } public DeclaracionProcesos getProcAST() { return this.procAST; } public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException { synchronized (this) {
package form; public class Robot { private int ciclos; private ArrayList<Coord> misCalles; private DeclaracionProcesos procAST; private Cuerpo cueAST; private DeclaracionVariable varAST; private ImageIcon robotImage; private ArrayList<Coord> ruta; private ArrayList<ArrayList<Coord>> rutas; public int Av; public int Ca; private int direccion; private final PropertyChangeSupport pcs; private Ciudad city; private int floresEnBolsa; private int papelesEnBolsa; private int floresEnBolsaDeConfiguracion; private int papelesEnBolsaDeConfiguracion; private ArrayList<Area> areas; MonitorEsquinas esquinas; MonitorActualizarVentana esperarRefresco; public int id; private static int cant; public int offsetAv; public int offsetCa; public String dir; public MonitorMensajes monitor; String nombre; Color color; public String estado; public Robot(final Ciudad city, final String nombre) throws Exception { this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotAbajo.png")); this.ruta = new ArrayList<Coord>(); this.rutas = new ArrayList<ArrayList<Coord>>(); this.Av = 0; this.Ca = 0; this.direccion = 90; this.pcs = new PropertyChangeSupport(this); this.floresEnBolsa = 0; this.papelesEnBolsa = 0; this.floresEnBolsaDeConfiguracion = 0; this.papelesEnBolsaDeConfiguracion = 0; this.esquinas = MonitorEsquinas.getInstance(); this.esperarRefresco = MonitorActualizarVentana.getInstance(); this.offsetAv = 0; this.offsetCa = 0; this.misCalles = new ArrayList<Coord>(); this.areas = new ArrayList<Area>(); this.Av = 0; this.Ca = 0; this.getRuta().add(new Coord(this.Av, this.Ca)); this.setNombre(nombre); this.city = city; this.rutas.add(this.ruta); this.id = this.getCity().robots.size(); this.color = this.getColorById(this.id); this.setDireccion(90); this.setFlores(this.getFloresEnBolsaDeConfiguracion()); this.setPapeles(this.getPapelesEnBolsaDeConfiguracion()); this.estado = "Nuevo "; } public void crear() throws UnknownHostException, IOException { this.dir = ""; System.out.println(this.getId()); if (this.id == 0) { final int puerto = 4000; File archivo = null; FileReader fr = null; BufferedReader br = null; archivo = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "Conf.txt"); try { fr = new FileReader(archivo); } catch (FileNotFoundException ex) { Logger.getLogger(Mover.class.getName()).log(Level.SEVERE, null, ex); } br = new BufferedReader(fr); String ip = null; String linea; while ((linea = br.readLine()) != null) { System.out.println(linea); final String[] lineas = linea.split(" "); final String robot = lineas[0]; ip = lineas[1]; System.out.println(" el robot es : " + robot + " y la ip es : " + ip); } this.dir = "192.168.0.100"; this.dir = ip; } else { System.out.println("Entre al else"); this.dir = "192.168.0.104"; final int puerto = 4000; } try (final Socket s = new Socket(this.dir, 4000)) { System.out.println("conectados"); final DataOutputStream dOut = new DataOutputStream(s.getOutputStream()); dOut.writeByte(this.getId()); dOut.flush(); dOut.close(); } } public int getCiclos() { return this.ciclos; } public void setCiclos(final int ciclos) { this.ciclos = ciclos; } public Color getColorById(final int id) { switch (id) { case 0: { return Color.RED; } case 1: { return new Color(0, 137, 221); } case 2: { return Color.PINK; } case 3: { return new Color(0, 153, 68); } case 4: { return Color.MAGENTA; } default: { final int max = 255; final int min = 1; final int x = (int) (Math.random() * (max - min + 1)) + min; final int y = (int) (Math.random() * (max - min + 1)) + min; final int z = (int) (Math.random() * (max - min + 1)) + min; return new Color(x, y, z); } } } public void almacenarMensaje(final String nombreDestino, final String valor) throws Exception { final Dato d = new Dato(valor, nombreDestino); final int id = this.getCity().getRobotByNombre(nombreDestino).id; this.monitor.llegoMensaje(id, d); } public void recibirMensaje(final Identificador nombreVariable, final int id, final Identificador NombreRobot) throws Exception { this.monitor.recibirMensaje(nombreVariable, id, NombreRobot); } public void Informar(final String msj) { this.getCity().Informar(msj, this.id); this.esperarRefresco.esperar(this.id); } public void bloquearEsquina(final int Av, final int Ca) { this.esquinas.bloquear(Av, Ca); this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); } public void liberarEsquina(final int Av, final int Ca) { this.esquinas.liberar(Av, Ca); this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); } public Cuerpo getCuerpo() { return this.cueAST; } public void agregarArea(final Area a) { this.areas.add(a); for (int i = a.getAv1(); i <= a.getAv2(); ++i) { for (int j = a.getCa1(); j <= a.getCa2(); ++j) { this.misCalles.add(new Coord(i, j)); } } } public boolean esAreaVacia() { return this.areas.isEmpty(); } public void crearMonitor(final int cant) { this.monitor = MonitorMensajes.crearMonitorActualizarVentana(cant, this); } public void setCuerpo(final Cuerpo cueAST) { this.cueAST = cueAST; } public DeclaracionVariable getVariables() { return this.varAST; } public void setVariables(final DeclaracionVariable varAST) { this.varAST = varAST; } public int getFloresEnBolsaDeConfiguracion() { return this.floresEnBolsaDeConfiguracion; } public void setFloresEnBolsaDeConfiguracion(final int floresEnBolsaDeConfiguracion) { this.setFlores(this.floresEnBolsaDeConfiguracion = floresEnBolsaDeConfiguracion); } public int getPapelesEnBolsaDeConfiguracion() { return this.papelesEnBolsaDeConfiguracion; } public void setPapelesEnBolsaDeConfiguracion(final int papelesEnBolsaDeConfiguracion) { this.setPapeles(this.papelesEnBolsaDeConfiguracion = papelesEnBolsaDeConfiguracion); } public void reset() { this.misCalles = new ArrayList<Coord>(); this.ruta = new ArrayList<Coord>(); this.rutas = new ArrayList<ArrayList<Coord>>(); this.areas = new ArrayList<Area>(); this.rutas.add(this.ruta); this.setFlores(this.getFloresEnBolsaDeConfiguracion()); this.setPapeles(this.getPapelesEnBolsaDeConfiguracion()); try { this.setAv(0); this.setCa(0); } catch (Exception ex) { Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex); } this.setDireccion(90); } public Image getImage() { switch (this.getDireccion()) { case 0: { this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotDerecha.png")); break; } case 90: { this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotArriba.png")); break; } case 180: { this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotIzquierda.png")); break; } default: { this.robotImage = new ImageIcon(this.getClass().getResource("/images/robotAbajo.png")); break; } } return this.robotImage.getImage(); } public String getNombre() { return this.nombre; } public void setNombre(final String nombre) { this.nombre = nombre; } public void iniciar(final int x, final int y) throws Exception { this.Pos(x, y); this.setNewX(x); this.setNewY(y); this.setFlores(this.getFlores()); this.setPapeles(this.getPapeles()); this.getCity().form.jsp.refresh(); } public void choque(final String nom, final int id, final int av, final int ca) throws Exception { for (final Robot r : this.getCity().robots) { if (r.id != id && r.Av == av && r.Ca == ca) { this.city.parseError(" Se produjo un choque entre el robot " + nom + " y el robot " + r.getNombre() + " en la avenida " + av + " y la calle " + ca); throw new Exception(" Se produjo un choque entre el robot " + nom + " y el robot " + r.getNombre() + " en la avenida " + av + " y la calle " + ca); } } } public void mover() throws Exception { int av = this.PosAv(); int ca = this.PosCa(); switch (this.getDireccion()) { case 0: { ++av; break; } case 180: { --av; break; } case 90: { ++ca; break; } case 270: { --ca; break; } } if (!this.puedeMover(av, ca, this.areas)) { this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que no corresponde a un area asignada del robot"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que no corresponde a un area asignada del robot"); } if (this.getCity().isFreePos(ca, av)) { this.addPos(av, ca); this.setFlores(this.getFlores()); this.setPapeles(this.getPapeles()); this.choque(this.nombre, this.id, this.Av, this.Ca); this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); return; } this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que hay un obst\u00e1culo"); throw new Exception("No se puede ejecutar la instrucci\u00f3n \"mover\" debido a que hay un obst\u00e1culo"); } public boolean puedeMover(final int av, final int ca, final ArrayList<Area> areas) { for (final Coord c : this.misCalles) { if (c.getX() == av && c.getY() == ca) { return true; } } return false; } public int[] getXCoord() { final int[] x = new int[this.ruta.size()]; for (int c = 0; c < this.ruta.size(); ++c) { final Coord p = this.ruta.get(c); x[c] = p.getX(); } return x; } public int[] getYCoord() { final int[] y = new int[this.ruta.size() + 1]; for (int c = 0; c < this.ruta.size(); ++c) { final Coord p = this.ruta.get(c); y[c] = p.getY(); } return y; } public void addPos(final int av, final int ca) throws Exception { try { final int old = this.city.ciudad[av][ca].getFlores(); this.setAv(av); this.setCa(ca); this.pcs.firePropertyChange("esquinaFlores", old, this.city.ciudad[av][ca].getFlores()); } catch (Exception e) { throw new Exception("Una de las nuevas coordenadas cae fuera de la ciudad.Av: " + av + " Ca: " + ca + " Calles: " + this.city.getNumCa() + " Avenidas: " + this.city.getNumAv()); } } public void setAv(final int av) throws Exception { if (av > this.city.getNumAv()) { throw new Exception(); } if (av != this.PosAv()) { this.ruta.add(new Coord(av, this.PosCa())); if (av > this.PosAv()) { this.setDireccion(0); } else { this.setDireccion(180); } } this.setNewX(av); this.setNewY(this.Ca); } public void setNewX(final int av) { final int old = this.PosAv(); this.Av = av; this.pcs.firePropertyChange("av", old, av); } public void setNewY(final int ca) { final int old = this.PosCa(); this.Ca = ca; this.pcs.firePropertyChange("ca", old, ca); } public void setCa(final int ca) throws Exception { if (ca > this.city.getNumCa()) { throw new Exception(); } if (ca != this.PosCa()) { this.ruta.add(new Coord(this.PosAv(), ca)); if (ca < this.PosCa()) { this.setDireccion(270); } else { this.setDireccion(90); } } this.setNewY(ca); this.setNewX(this.Av); } public void setDireccion(final int direccion) { final int old = this.direccion; this.direccion = direccion; this.pcs.firePropertyChange("direccion", old, direccion); } public void setEstado(final String str) { final String s = this.getEstado(); this.estado = str; this.pcs.firePropertyChange("estado", s, str); } public String getEstado() { return this.estado; } public int getDireccion() { return this.direccion; } public void addPropertyChangeListener(final PropertyChangeListener listener) { this.pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(final PropertyChangeListener listener) { this.pcs.removePropertyChangeListener(listener); } public void mirarEnDireccion(final int direccion) throws Exception { int c; for (c = 0; c < 5 && this.getDireccion() != direccion; ++c) { this.derecha(); } if (c == 5) { throw new Exception("La direcci\u00f3n especificada no corresponde."); } } public void izquierda() { switch (this.getDireccion()) { case 0: { this.setDireccion(90); break; } case 270: { this.setDireccion(0); break; } case 180: { this.setDireccion(270); break; } case 90: { this.setDireccion(180); break; } } this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); } public void derecha() { switch (this.getDireccion()) { case 0: { this.setDireccion(270); break; } case 270: { this.setDireccion(180); break; } case 180: { this.setDireccion(90); break; } case 90: { this.setDireccion(0); break; } } this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); } public int PosCa() { return this.Ca; } public int PosAv() { return this.Av; } public void Pos(final int Av, final int Ca) throws Exception { if (!this.puedeMover(Av, Ca, this.areas)) { this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que no corresponde a un area asignada del robot"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que no corresponde a un area asignada del robot"); } if (this.getCity().isFreePos(Ca, Av)) { this.getRutas().add(this.getRuta()); this.setRuta(new ArrayList<Coord>()); this.getRuta().add(new Coord(Av, Ca)); this.setNewX(Av); this.setNewY(Ca); this.choque(this.nombre, this.id, Av, Ca); this.esperarRefresco.esperar(this.id); this.getCity().form.jsp.refresh(); return; } this.city.parseError("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo"); throw new Exception("No se puede ejecutar la instrucci\u00f3n \"Pos\" debido a que hay un obst\u00e1culo"); } public ArrayList<Coord> getRuta() { return this.ruta; } public Ciudad getCity() { return this.city; } public void tomarFlor() throws Exception { if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) { this.setFlores(this.getFlores() + 1); this.esperarRefresco.esperar(this.id); return; } this.setFlores(this.getFlores()); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"tomarFlor\" debido a que no hay ninguna flor en la esquina"); } public int getFlores() { return this.floresEnBolsa; } public void setFlores(final int flores) { final int old = this.getFlores(); this.floresEnBolsa = flores; this.pcs.firePropertyChange("flores", old, flores); } public void tomarPapel() throws Exception { if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) { this.setPapeles(this.getPapeles() + 1); this.esperarRefresco.esperar(this.id); return; } this.setPapeles(this.getPapeles()); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"tomarPapel\" debido a que no hay ningun papel en la esquina"); } public boolean HayPapelEnLaBolsa() { return this.getPapeles() > 0; } public boolean HayFlorEnLaBolsa() { return this.getFlores() > 0; } public int getPapeles() { return this.papelesEnBolsa; } public void setColor(final Color col) { final Color old = this.color; this.color = col; this.pcs.firePropertyChange("color", old, col); } public Color getColor() { return this.color; } public void setPapeles(final int papeles) { final int old = this.getPapeles(); this.papelesEnBolsa = papeles; this.pcs.firePropertyChange("papeles", old, papeles); } public void depositarPapel() throws Exception { if (this.getPapeles() > 0) { this.setPapeles(this.getPapeles() - 1); this.getCity().dejarPapel(this.PosAv(), this.PosCa()); this.esperarRefresco.esperar(this.id); return; } this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"depositarPapel\" debido a que no hay ningun papel en la bolsa"); } public void depositarFlor() throws Exception { if (this.getFlores() > 0) { this.setFlores(this.getFlores() - 1); this.getCity().dejarFlor(this.PosAv(), this.PosCa()); this.esperarRefresco.esperar(this.id); return; } this.city.parseError( "No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores"); throw new Exception( "No se puede ejecutar la instrucci\u00f3n \"depositarFlor\" debido a que no hay ninguna en la bolsa de flores"); } public ArrayList<ArrayList<Coord>> getRutas() { return this.rutas; } public void setRuta(final ArrayList<Coord> ruta) { this.ruta = ruta; } public void setRutas(final ArrayList<ArrayList<Coord>> rutas) { this.rutas = rutas; } public DeclaracionProcesos getProcAST() { return this.procAST; } public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException { synchronized (this) {
final ArrayList<Proceso> ps = new ArrayList<Proceso>();
3
2023-10-20 15:45:37+00:00
8k
wevez/ClientCoderPack
src/tech/tenamen/Main.java
[ { "identifier": "Client", "path": "src/tech/tenamen/client/Client.java", "snippet": "public class Client implements Downloadable {\n\n private String VERSION_NAME;\n private File JSON_FILE, JAR_FILE;\n\n private final List<Library> LIBRARIES = new ArrayList<>();\n public Asset asset;\n\n private int javaMajorVersion = -1;\n\n public Client(final File folder) throws Exception {\n if (!folder.isFile()) {\n final List<File> JSON_CANDIDATE = new ArrayList<>(), JAR_CANDIDATE = new ArrayList<>();\n // collect json and jar candidates\n for (final File f : Objects.requireNonNull(folder.listFiles())) {\n if (!f.isFile()) continue;\n final String upperFileName = f.getName().toUpperCase();\n if (upperFileName.endsWith(\".JSON\")) {\n JSON_CANDIDATE.add(f);\n } else if (upperFileName.endsWith(\".JAR\")) {\n JAR_CANDIDATE.add(f);\n }\n }\n for (File jsonCandidate : JSON_CANDIDATE) {\n final String jsonFileRawName = jsonCandidate.getName();\n final String jsonFileName = jsonFileRawName.substring(0, jsonFileRawName.length() - \".json\".length());\n for (File jarCandidate : JAR_CANDIDATE) {\n final String jarFileRawName = jarCandidate.getName();\n final String jarFileName = jarFileRawName.substring(0, jarFileRawName.length() - \".jar\".length());\n if (jsonFileName.equalsIgnoreCase(jarFileName)) {\n this.VERSION_NAME = jsonFileName;\n this.JAR_FILE = jarCandidate;\n this.JSON_FILE = jsonCandidate;\n break;\n }\n }\n if (JSON_FILE != null && JAR_FILE != null && VERSION_NAME != null) break;\n }\n if (JSON_FILE == null) throw new Exception(\"The folder doesn't have json\");\n if (JAR_FILE == null) throw new Exception(\"The folder doesn't have jar\");\n if (VERSION_NAME == null) throw new Exception(\"The name is null\");\n } else {\n throw new Exception(\"The folder is not folder\");\n }\n }\n\n public void parseDependencies() {\n JsonObject object = null;\n try {\n object = new GsonBuilder().setPrettyPrinting().create().fromJson(new FileReader(this.JSON_FILE), JsonObject.class);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n if (object == null) return;\n // arguments\n if (object.has(\"arguments\")) {\n // TODO make launch property from json\n final JsonObject arguments = object.getAsJsonObject(\"arguments\");\n }\n // asset index\n if (object.has(\"assetIndex\")) {\n final JsonObject assetIndex = object.getAsJsonObject(\"assetIndex\");\n String assetId = null, assetSha1 = null, assetUrl = null;\n long assetSize = -1, assetTutorialSize = -1;\n if (assetIndex.has(\"id\")) assetId = assetIndex.get(\"id\").getAsString();\n if (assetIndex.has(\"sha1\")) assetSha1 = assetIndex.get(\"sha1\").getAsString();\n if (assetIndex.has(\"url\")) assetUrl = assetIndex.get(\"url\").getAsString();\n if (assetIndex.has(\"size\")) assetSize = assetIndex.get(\"size\").getAsLong();\n if (assetIndex.has(\"totalSize\")) assetTutorialSize = assetIndex.get(\"totalSize\").getAsLong();\n if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) {\n asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl);\n }\n }\n // downloads\n if (object.has(\"downloads\")) {\n final JsonObject downloads = object.getAsJsonObject(\"downloads\");\n if (downloads.has(\"client\")) {\n final JsonObject client = downloads.getAsJsonObject(\"client\");\n new Thread(() -> {\n NetUtil.download(client.get(\"url\").getAsString(), new File(Main.LIBRARIES_DIR, \"client.jar\"));\n }).start();\n Main.IDE.getLibraryNames().add(\"client.jar\");\n }\n if (downloads.has(\"client_mappings\")) {\n final JsonObject clientMappings = downloads.getAsJsonObject(\"client_mappings\");\n }\n if (downloads.has(\"server\")) {\n final JsonObject server = downloads.getAsJsonObject(\"server\");\n }\n if (downloads.has(\"server_mappings\")) {\n final JsonObject serverMappings = downloads.getAsJsonObject(\"server_mappings\");\n }\n }\n // java version\n if (object.has(\"javaVersion\")) {\n final JsonObject javaVersion = object.getAsJsonObject(\"javaVersion\");\n // if (javaVersion.has(\"component\"))\n if (javaVersion.has(\"majorVersion\")) this.javaMajorVersion = javaVersion.get(\"majorVersion\").getAsInt();\n }\n if (object.has(\"libraries\")) {\n final JsonArray libraries = object.getAsJsonArray(\"libraries\");\n for (JsonElement e : libraries) {\n String libName = null, libPath = null, libSha1 = null, libUrl = null;\n long libSize = -1;\n final OSRule osRule = new OSRule();\n final List<NativeLibrary> nativeLibraries = new ArrayList<>();\n final JsonObject library = e.getAsJsonObject();\n if (library.has(\"downloads\")) {\n final JsonObject downloads = library.getAsJsonObject(\"downloads\");\n if (downloads.has(\"artifact\")) {\n final JsonObject artifact = downloads.getAsJsonObject(\"artifact\");\n if (artifact.has(\"path\")) libPath = artifact.get(\"path\").getAsString();\n if (artifact.has(\"sha1\")) libSha1 = artifact.get(\"sha1\").getAsString();\n if (artifact.has(\"url\")) libUrl = artifact.get(\"url\").getAsString();\n if (artifact.has(\"size\")) libSize = artifact.get(\"size\").getAsLong();\n }\n if (downloads.has(\"classifiers\")) {\n final JsonObject classifiers = downloads.getAsJsonObject(\"classifiers\");\n final Map<String, JsonObject> nativeObjects = new HashMap<>();\n if (classifiers.has(\"natives-windows\")) {\n nativeObjects.put(\"natives-windows\", classifiers.getAsJsonObject(\"natives-windows\"));\n }\n if (classifiers.has(\"natives-linux\")) {\n nativeObjects.put(\"natives-linux\", classifiers.getAsJsonObject(\"natives-linux\"));\n }\n if (classifiers.has(\"natives-macos\")) {\n nativeObjects.put(\"natives-macos\", classifiers.getAsJsonObject(\"natives-macos\"));\n }\n nativeObjects.forEach((k, v) -> {\n String nativePath = null, nativeSha1 = null, nativeUrl = null;\n long nativeSize = -1;\n if (v.has(\"path\")) nativePath = v.get(\"path\").getAsString();\n if (v.has(\"sha1\")) nativeSha1 = v.get(\"sha1\").getAsString();\n if (v.has(\"url\")) nativeUrl = v.get(\"url\").getAsString();\n if (v.has(\"size\")) nativeSize = v.get(\"size\").getAsLong();\n if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) {\n nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl));\n }\n });\n }\n }\n if (library.has(\"name\")) {\n libName = library.get(\"name\").getAsString();\n }\n if (library.has(\"rules\")) {\n for (JsonElement r : library.getAsJsonArray(\"rules\")) {\n // os\n final JsonObject rule = r.getAsJsonObject();\n if (rule.has(\"action\")) {\n final String action = rule.get(\"action\").getAsString();\n osRule.setAllow(action.equalsIgnoreCase(\"allow\"));\n }\n if (rule.has(\"os\")) {\n final JsonObject os = rule.getAsJsonObject(\"os\");\n if (os.has(\"name\")) osRule.setOSName(os.get(\"name\").getAsString());\n }\n }\n }\n if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) {\n this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries));\n }\n }\n }\n // release time\n if (object.has(\"releaseTime\")) {\n final String releaseTime = object.get(\"releaseTime\").getAsString();\n }\n // time\n if (object.has(\"time\")) {\n final String time = object.get(\"time\").getAsString();\n }\n // type\n if (object.has(\"type\")) {\n final String type = object.get(\"type\").getAsString();\n }\n Main.IDE.getLibraryNames().add(\"jsr305-3.0.2.jar\");\n }\n\n public final String getVersionName() { return this.VERSION_NAME; }\n\n @Override\n public void download(OS os) {\n final List<Thread> threads = new ArrayList<>();\n this.LIBRARIES.forEach(l -> {\n threads.add(new Thread(() -> {\n l.download(os);\n }));\n });\n this.asset.download(os);\n threads.addAll(this.asset.threads);\n for (Thread thread : threads) {\n thread.run();\n }\n for (Thread thread : threads) {\n try {\n thread.join();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n public int getJavaMajorVersion() { return this.javaMajorVersion; }\n\n}" }, { "identifier": "IDE", "path": "src/tech/tenamen/ide/IDE.java", "snippet": "public abstract class IDE {\n\n private final List<String> LIBRARY_NAMES = new ArrayList<>();\n private final List<String> NATIVE_NAMES = new ArrayList<>();\n\n public final List<String> getLibraryNames() { return this.LIBRARY_NAMES; }\n public final List<String> getNativeNames() { return this.NATIVE_NAMES; }\n\n public abstract void createProperties();\n\n}" }, { "identifier": "InteliJIDE", "path": "src/tech/tenamen/ide/InteliJIDE.java", "snippet": "public class InteliJIDE extends IDE {\n\n private static File PROPERTY_DIR, IDE_LIBRARIES_DIR;\n\n @Override\n public void createProperties() {\n PROPERTY_DIR = new File(Main.WORKING_DIR, \".idea\");\n PROPERTY_DIR.mkdirs();\n IDE_LIBRARIES_DIR = new File(PROPERTY_DIR, \"libraries\");\n IDE_LIBRARIES_DIR.mkdirs();\n // .gitignore\n System.out.println(\"Making .gitignore\");\n this.makeGitignore();\n // .name\n System.out.println(\"Making .name\");\n this.makeName();\n // misc.xml\n System.out.println(\"Making misc.xml\");\n this.makeMisc();\n // modules.xml\n System.out.println(\"Making modules.xml\");\n this.makeModules();\n // vcs.xml\n System.out.println(\"Making vcs.xml\");\n this.makeVCS();\n // workspace.xml\n System.out.println(\"Making workspace.xml\");\n this.makeWorkspace();\n // libraries\n System.out.println(\"Making libraries\");\n this.makeLibraries();\n // iml\n System.out.println(\"Making iml\");\n this.makeIml();\n }\n\n private void makeGitignore() {\n final File gitignoreFile = new File(PROPERTY_DIR, \".gitignore\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"# Default ignored files\\n/shelf/\\n/workspace.xml\\n\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeName() {\n final File gitignoreFile = new File(PROPERTY_DIR, \".name\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(Main.WORKING_DIR.getName());\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeMisc() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"misc.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(String.format(\" <component name=\\\"ProjectRootManager\\\" version=\\\"2\\\" languageLevel=\\\"JDK_%d\\\" default=\\\"true\\\" project-jdk-name=\\\"%d\\\" project-jdk-type=\\\"JavaSDK\\\">\\n\",\n Main.client.getJavaMajorVersion(), Main.client.getJavaMajorVersion()));\n writer.write(\" <output url=\\\"file://$PROJECT_DIR$/out\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeModules() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"modules.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"ProjectModuleManager\\\">\\n\");\n writer.write(\" <modules>\\n\");\n writer.write(String.format(\" <module fileurl=\\\"file://$PROJECT_DIR$/%s.iml\\\" filepath=\\\"$PROJECT_DIR$/%s.iml\\\" />\\n\",\n Main.WORKING_DIR.getName(), Main.WORKING_DIR.getName()));\n writer.write(\" </modules>\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeVCS() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"vcs.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"VcsDirectoryMappings\\\">\\n\");\n writer.write(\" <mapping directory=\\\"\\\" vcs=\\\"Git\\\" />\\n\");\n writer.write(\" <mapping directory=\\\"$PROJECT_DIR$\\\" vcs=\\\"Git\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeWorkspace() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"workspace.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeLibraries() {\n final File gitignoreFile = new File(IDE_LIBRARIES_DIR, \"ccp.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<component name=\\\"libraryTable\\\">\\n\");\n writer.write(\" <library name=\\\"ccp\\\">\\n\");\n writer.write(\" <CLASSES>\\n\");\n for (String libraryName : this.getLibraryNames()) {\n writer.write(String.format(\" <root url=\\\"jar://$PROJECT_DIR$/libraries/%s!/\\\" />\\n\", libraryName));\n }\n writer.write(\" </CLASSES>\\n\");\n writer.write(\" <JAVADOC />\\n\");\n writer.write(\" <NATIVE>\\n\");\n writer.write(\" <root url=\\\"file://$PROJECT_DIR$/libraries/natives\\\" />\\n\");\n writer.write(\" </NATIVE>\\n\");\n writer.write(\" <SOURCES />\\n\");\n writer.write(\" </library>\\n\");\n writer.write(\"</component>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeIml() {\n final File gitignoreFile = new File(Main.WORKING_DIR, String.format(\"%s.iml\", Main.WORKING_DIR.getName()));\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<module type=\\\"JAVA_MODULE\\\" version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"NewModuleRootManager\\\" inherit-compiler-output=\\\"true\\\">\\n\");\n writer.write(\" <exclude-output />\\n\");\n writer.write(\" <content url=\\\"file://$MODULE_DIR$\\\">\\n\");\n writer.write(\" <sourceFolder url=\\\"file://$MODULE_DIR$/src\\\" isTestSource=\\\"false\\\" />\\n\");\n writer.write(\" </content>\\n\");\n writer.write(\" <orderEntry type=\\\"inheritedJdk\\\" />\\n\");\n writer.write(\" <orderEntry type=\\\"sourceFolder\\\" forTests=\\\"false\\\" />\\n\");\n writer.write(\" <orderEntry type=\\\"library\\\" name=\\\"ccp\\\" level=\\\"project\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</module>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" }, { "identifier": "OS", "path": "src/tech/tenamen/property/OS.java", "snippet": "public enum OS {\n\n WINDOWS(\"windows\", \"natives-windows\"),\n MAC(\"osx\", \"natives-macos\"),\n LINUX(\"linux\", \"natives-linux\");\n\n private final String OS_RULE_NAME, NATIVE_OS_NAME;\n\n OS(final String OS_RULE_NAME, final String NATIVE_OS_NAME) {\n this.OS_RULE_NAME = OS_RULE_NAME;\n this.NATIVE_OS_NAME = NATIVE_OS_NAME;\n }\n\n public String toOsRule() { return OS_RULE_NAME; }\n public String toNativeOs() { return NATIVE_OS_NAME; }\n}" } ]
import tech.tenamen.client.Client; import tech.tenamen.ide.IDE; import tech.tenamen.ide.InteliJIDE; import tech.tenamen.property.OS; import java.io.File; import java.util.Scanner;
4,623
package tech.tenamen; public class Main { public static IDE IDE = new InteliJIDE(); public static Client client; public static File WORKING_DIR = new File(System.getProperty("user.dir")), ASSETS_DIR = new File(WORKING_DIR, "assets"), LIBRARIES_DIR = new File(WORKING_DIR, "libraries"), OBJECTS_DIR = new File(ASSETS_DIR, "objects"), INDEXES_DIR = new File(ASSETS_DIR, "indexes"), SRC_DIR = new File(WORKING_DIR, "src"), NATIVES_DIR = new File(LIBRARIES_DIR, "natives"); public static void main(String[] main) throws Exception { final Scanner scanner = new Scanner(System.in); System.out.println("ClientCoderPack"); System.out.print("Version<<"); final File versionFile = new File(String.format("%s\\.minecraft\\versions\\%s", System.getenv("APPDATA"), scanner.next())); if (!versionFile.exists()) { System.out.printf("File %s not found%n", versionFile.getAbsolutePath()); return; } ASSETS_DIR.mkdirs(); LIBRARIES_DIR.mkdirs(); OBJECTS_DIR.mkdirs(); INDEXES_DIR.mkdirs(); SRC_DIR.mkdirs(); NATIVES_DIR.mkdirs(); client = new Client(versionFile); System.out.println("Downloading dependencies"); client.parseDependencies(); client.download(getOs()); System.out.println("Making IDE property file"); IDE.createProperties(); System.out.println("Process has finished!"); }
package tech.tenamen; public class Main { public static IDE IDE = new InteliJIDE(); public static Client client; public static File WORKING_DIR = new File(System.getProperty("user.dir")), ASSETS_DIR = new File(WORKING_DIR, "assets"), LIBRARIES_DIR = new File(WORKING_DIR, "libraries"), OBJECTS_DIR = new File(ASSETS_DIR, "objects"), INDEXES_DIR = new File(ASSETS_DIR, "indexes"), SRC_DIR = new File(WORKING_DIR, "src"), NATIVES_DIR = new File(LIBRARIES_DIR, "natives"); public static void main(String[] main) throws Exception { final Scanner scanner = new Scanner(System.in); System.out.println("ClientCoderPack"); System.out.print("Version<<"); final File versionFile = new File(String.format("%s\\.minecraft\\versions\\%s", System.getenv("APPDATA"), scanner.next())); if (!versionFile.exists()) { System.out.printf("File %s not found%n", versionFile.getAbsolutePath()); return; } ASSETS_DIR.mkdirs(); LIBRARIES_DIR.mkdirs(); OBJECTS_DIR.mkdirs(); INDEXES_DIR.mkdirs(); SRC_DIR.mkdirs(); NATIVES_DIR.mkdirs(); client = new Client(versionFile); System.out.println("Downloading dependencies"); client.parseDependencies(); client.download(getOs()); System.out.println("Making IDE property file"); IDE.createProperties(); System.out.println("Process has finished!"); }
private static OS getOs() {
3
2023-10-20 06:56:19+00:00
8k
Invadermonky/Omniwand
src/main/java/com/invadermonky/omniwand/proxy/ClientProxy.java
[ { "identifier": "GuiWand", "path": "src/main/java/com/invadermonky/omniwand/client/GuiWand.java", "snippet": "public class GuiWand extends GuiScreen {\n ItemStack wand;\n\n public GuiWand(ItemStack wand) {\n this.wand = wand;\n }\n\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n super.drawScreen(mouseX, mouseY, partialTicks);\n ArrayList<ItemStack> stacks = new ArrayList<>();\n\n if(this.wand.hasTagCompound()) {\n NBTTagCompound data = this.wand.getTagCompound().getCompoundTag(References.TAG_WAND_DATA);\n ArrayList<String> keys = new ArrayList<>(data.getKeySet());\n Collections.sort(keys);\n\n for(String key : keys) {\n NBTTagCompound compoundTag = data.getCompoundTag(key);\n\n if(compoundTag != null)\n stacks.add(new ItemStack(compoundTag));\n }\n }\n\n ScaledResolution res = new ScaledResolution(this.mc);\n int centerX = res.getScaledWidth() / 2;\n int centerY = res.getScaledHeight() / 2;\n int amountPerRow = Math.min(12, Math.max(8, stacks.size() / 3));\n int rows = (int) Math.ceil((double) stacks.size() / amountPerRow);\n int iconSize = 20;\n int startX = centerX - amountPerRow * iconSize / 2;\n int startY = centerY - rows * iconSize + Math.min(90, Math.max(40, 10 * rows));\n int padding = 4;\n int extra = 2;\n\n drawRect(startX - padding, startY - padding, startX + iconSize * amountPerRow + padding, startY + iconSize * rows + padding, 570425344);\n drawRect(startX - padding - extra, startY - padding - extra, startX + iconSize * amountPerRow + padding + extra, startY + iconSize * rows + padding + extra, 570425344);\n\n ItemStack tooltipStack = ItemStack.EMPTY;\n\n if(!stacks.isEmpty()) {\n RenderHelper.enableGUIStandardItemLighting();\n\n for(int i = 0; i < stacks.size(); i++) {\n int x = startX + i % amountPerRow * iconSize;\n int y = startY + i / amountPerRow * iconSize;\n ItemStack stack = stacks.get(i);\n if(mouseX > x && mouseY > y && mouseX <= x + 16 && mouseY <= y + 16) {\n tooltipStack = stack;\n y -= 2;\n }\n this.itemRender.renderItemAndEffectIntoGUI(stack, x, y);\n }\n RenderHelper.disableStandardItemLighting();\n }\n\n if(!tooltipStack.isEmpty()) {\n String name = NBTHelper.getString(tooltipStack, References.TAG_WAND_DISPLAY_NAME, tooltipStack.getDisplayName());\n String definedMod = TransformHandler.getModFromStack(tooltipStack);\n String mod = TextFormatting.GRAY + TransformHandler.getModNameForId(definedMod);\n definedMod = NBTHelper.getString(tooltipStack, References.TAG_ITEM_DEFINED_MOD, definedMod);\n renderTooltip(mouseX, mouseY, Arrays.asList(name, mod));\n\n if(Mouse.isButtonDown(0)) {\n Omniwand.network.sendToServer(new MessageGuiTransform(definedMod));\n TransformHandler.autoMode = false;\n this.mc.displayGuiScreen(null);\n }\n }\n }\n\n @SideOnly(Side.CLIENT)\n public static void renderTooltip(int x, int y, List<String> tooltipData) {\n int color1 = 1347420415;\n int color2 = -267386864;\n\n boolean lighting = GL11.glGetBoolean(2896);\n if(lighting)\n RenderHelper.disableStandardItemLighting();\n\n if (!tooltipData.isEmpty()) {\n int var1 = 0;\n FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;\n\n int var2;\n int var3;\n for(var2 = 0; var2 < tooltipData.size(); ++var2) {\n var3 = fontRenderer.getStringWidth(tooltipData.get(var2));\n if (var3 > var1) {\n var1 = var3;\n }\n }\n\n var2 = x + 12;\n var3 = y - 12;\n int var4 = 8;\n if (tooltipData.size() > 1) {\n var4 += 2 + (tooltipData.size() - 1) * 10;\n }\n\n ScaledResolution res = new ScaledResolution(Minecraft.getMinecraft());\n int right = var2 + var1 + 5;\n int scaledWidth = res.getScaledWidth();\n int bottom;\n if (right > scaledWidth) {\n bottom = right - scaledWidth;\n var2 -= bottom;\n }\n\n bottom = var3 + var4 + 5;\n int scaledHeight = res.getScaledHeight();\n if (bottom > scaledHeight) {\n int diff = bottom - scaledHeight;\n var3 -= diff;\n }\n\n float z = 300.0F;\n drawGradientRect(var2 - 3, var3 - 4, z, var2 + var1 + 3, var3 - 3, color2, color2);\n drawGradientRect(var2 - 3, var3 + var4 + 3, z, var2 + var1 + 3, var3 + var4 + 4, color2, color2);\n drawGradientRect(var2 - 3, var3 - 3, z, var2 + var1 + 3, var3 + var4 + 3, color2, color2);\n drawGradientRect(var2 - 4, var3 - 3, z, var2 - 3, var3 + var4 + 3, color2, color2);\n drawGradientRect(var2 + var1 + 3, var3 - 3, z, var2 + var1 + 4, var3 + var4 + 3, color2, color2);\n\n int var5 = (color1 & 16777215) >> 1 | color1 & -16777216;\n drawGradientRect(var2 - 3, var3 - 3 + 1, z, var2 - 3 + 1, var3 + var4 + 3 - 1, color1, var5);\n drawGradientRect(var2 + var1 + 2, var3 - 3 + 1, z, var2 + var1 + 3, var3 + var4 + 3 - 1, color1, var5);\n drawGradientRect(var2 - 3, var3 - 3, z, var2 + var1 + 3, var3 - 3 + 1, color1, color1);\n drawGradientRect(var2 - 3, var3 + var4 + 2, z, var2 + var1 + 3, var3 + var4 + 3, var5, var5);\n\n GlStateManager.disableDepth();\n\n for(int i = 0; i < tooltipData.size(); i++) {\n String tooltip = tooltipData.get(i);\n fontRenderer.drawStringWithShadow(tooltip, (float)var2, (float)var3, -1);\n if (i == 0) {\n var3 += 2;\n }\n\n var3 += 10;\n }\n GlStateManager.enableDepth();\n }\n\n if (!lighting)\n RenderHelper.disableStandardItemLighting();\n\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\n }\n\n @SideOnly(Side.CLIENT)\n public static void drawGradientRect(int par1, int par2, float z, int par3, int par4, int par5, int par6) {\n float red_1 = (float)(par5 >> 24 & 255) / 255.0F;\n float green_1 = (float)(par5 >> 16 & 255) / 255.0F;\n float blue_1 = (float)(par5 >> 8 & 255) / 255.0F;\n float alpha_1 = (float)(par5 & 255) / 255.0F;\n float red_2 = (float)(par6 >> 24 & 255) / 255.0F;\n float green_2 = (float)(par6 >> 16 & 255) / 255.0F;\n float blue_2 = (float)(par6 >> 8 & 255) / 255.0F;\n float alpha_2 = (float)(par6 & 255) / 255.0F;\n\n GlStateManager.disableTexture2D();\n GlStateManager.enableBlend();\n GlStateManager.disableAlpha();\n GlStateManager.blendFunc(770, 771);\n GlStateManager.shadeModel(7425);\n\n Tessellator tessellator = Tessellator.getInstance();\n\n BufferBuilder buff = tessellator.getBuffer();\n buff.begin(7, DefaultVertexFormats.POSITION_COLOR);\n buff.pos(par3, par2, z).color(green_1, blue_1, alpha_1, red_1).endVertex();\n buff.pos(par1, par2, z).color(green_1, blue_1, alpha_1, red_1).endVertex();\n buff.pos(par1, par4, z).color(green_2, blue_2, alpha_2, red_2).endVertex();\n buff.pos(par3, par4, z).color(green_2, blue_2, alpha_2, red_2).endVertex();\n\n tessellator.draw();\n GlStateManager.shadeModel(7424);\n GlStateManager.disableBlend();\n GlStateManager.enableAlpha();\n GlStateManager.enableTexture2D();\n }\n}" }, { "identifier": "ConfigHandler", "path": "src/main/java/com/invadermonky/omniwand/handlers/ConfigHandler.java", "snippet": "public class ConfigHandler {\n public static Configuration config = null;\n\n public static boolean enableTransform;\n public static boolean offhandTransform;\n public static boolean restrictTooltip;\n public static boolean crouchRevert;\n public static boolean alternateAppearance;\n public static THashSet<String> transformItems;\n public static THashMap<String,String> modAliases;\n public static THashSet<String> blacklistedMods;\n public static THashSet<String> whitelistedItems;\n public static THashSet<String> whiteListedNames;\n\n public static void preInit() {\n File configFile = new File(Paths.get(Loader.instance().getConfigDir().toString(), Omniwand.MOD_ID + \".cfg\").toString());\n config = new Configuration(configFile);\n config.load();\n setPropertyOrder();\n loadConfig();\n }\n\n private static void setPropertyOrder() {\n List<String> propOrder = new ArrayList<>();\n\n propOrder.add(References.ENABLE_TRANSFORM.getName());\n propOrder.add(References.RESTRICT_TOOLTIP.getName());\n propOrder.add(References.OFFHAND_TRANSFORM.getName());\n propOrder.add(References.CROUCH_REVERT.getName());\n propOrder.add(References.ALT_APPEARANCE.getName());\n propOrder.add(References.TRANSFORM_ITEMS.getName());\n propOrder.add(References.MOD_ALIASES.getName());\n propOrder.add(References.BLACKLIST_MODS.getName());\n propOrder.add(References.WHITELIST_ITEMS.getName());\n propOrder.add(References.WHITELIST_NAMES.getName());\n\n config.setCategoryPropertyOrder(Configuration.CATEGORY_GENERAL, propOrder);\n }\n\n public static void loadConfig() {\n enableTransform = config.getBoolean(\n References.ENABLE_TRANSFORM.getName(),\n Configuration.CATEGORY_GENERAL,\n References.ENABLE_TRANSFORM.getBoolean(),\n References.ENABLE_TRANSFORM.getComment()\n );\n\n restrictTooltip = config.getBoolean(\n References.RESTRICT_TOOLTIP.getName(),\n Configuration.CATEGORY_GENERAL,\n References.RESTRICT_TOOLTIP.getBoolean(),\n References.RESTRICT_TOOLTIP.getComment()\n );\n\n offhandTransform = config.getBoolean(\n References.OFFHAND_TRANSFORM.getName(),\n Configuration.CATEGORY_GENERAL,\n References.OFFHAND_TRANSFORM.getBoolean(),\n References.OFFHAND_TRANSFORM.getComment()\n );\n\n crouchRevert = config.getBoolean(\n References.CROUCH_REVERT.getName(),\n Configuration.CATEGORY_GENERAL,\n References.CROUCH_REVERT.getBoolean(),\n References.CROUCH_REVERT.getComment()\n );\n\n alternateAppearance = config.getBoolean(\n References.ALT_APPEARANCE.getName(),\n Configuration.CATEGORY_GENERAL,\n References.ALT_APPEARANCE.getBoolean(),\n References.ALT_APPEARANCE.getComment()\n );\n\n String[] a_transformItems = config.getStringList(\n References.TRANSFORM_ITEMS.getName(),\n Configuration.CATEGORY_GENERAL,\n References.TRANSFORM_ITEMS.getDefaults(),\n References.TRANSFORM_ITEMS.getComment()\n );\n\n String[] a_modAliases = config.getStringList(\n References.MOD_ALIASES.getName(),\n Configuration.CATEGORY_GENERAL,\n References.MOD_ALIASES.getDefaults(),\n References.MOD_ALIASES.getComment()\n );\n\n String[] a_blacklistedMods = config.getStringList(\n References.BLACKLIST_MODS.getName(),\n Configuration.CATEGORY_GENERAL,\n References.BLACKLIST_MODS.getDefaults(),\n References.BLACKLIST_MODS.getComment()\n );\n\n String[] a_whitelistedItems = config.getStringList(\n References.WHITELIST_ITEMS.getName(),\n Configuration.CATEGORY_GENERAL,\n References.WHITELIST_ITEMS.getDefaults(),\n References.WHITELIST_ITEMS.getComment()\n );\n\n String[] a_whitelistedNames = config.getStringList(\n References.WHITELIST_NAMES.getName(),\n Configuration.CATEGORY_GENERAL,\n References.WHITELIST_NAMES.getDefaults(),\n References.WHITELIST_NAMES.getComment()\n );\n\n //Converting Arrays to HashSets/HashMaps\n transformItems = getStringHashSet(a_transformItems);\n modAliases = getStringHashMap(a_modAliases);\n blacklistedMods = getStringHashSet(a_blacklistedMods);\n whitelistedItems = getStringHashSet(a_whitelistedItems);\n whiteListedNames = getStringHashSet(a_whitelistedNames);\n\n if(config.hasChanged())\n config.save();\n }\n\n private static THashMap<String,String> getStringHashMap(String[] array) {\n THashMap<String,String> map = new THashMap<>();\n for(String entry : array) {\n String[] split = entry.split(\"=\");\n if(split.length != 2)\n continue;\n map.put(split[0], split[1]);\n }\n return map;\n }\n\n private static THashSet<String> getStringHashSet(String[] array) {\n return new THashSet<>(Sets.newHashSet(array));\n }\n\n public static EnumHand getConfiguredHand() {\n return offhandTransform ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND;\n }\n\n @SubscribeEvent\n public void onConfigChange(ConfigChangedEvent.OnConfigChangedEvent event) {\n if(event.getModID().equals(Omniwand.MOD_ID))\n loadConfig();\n }\n}" }, { "identifier": "MouseEventOW", "path": "src/main/java/com/invadermonky/omniwand/handlers/MouseEventOW.java", "snippet": "@SideOnly(Side.CLIENT)\npublic class MouseEventOW {\n public static final MouseEventOW INSTANCE = new MouseEventOW();\n\n @SubscribeEvent(priority = EventPriority.HIGHEST)\n public void onMouseEvent(MouseEvent event) {\n EntityPlayerSP playerSP = Minecraft.getMinecraft().player;\n ItemStack heldItem = playerSP.getHeldItem(ConfigHandler.getConfiguredHand());\n\n if(TransformHandler.isOmniwand(heldItem)) {\n ItemStack newStack = heldItem;\n RayTraceResult result = RayTracer.retrace(playerSP);\n String modLook = \"\";\n\n //Look transform\n if(ConfigHandler.enableTransform && result != null) {\n IBlockState state = playerSP.world.getBlockState(result.getBlockPos());\n modLook = TransformHandler.getModFromState(state);\n if (TransformHandler.autoMode && event.getDwheel() == 0) {\n newStack = TransformHandler.getTransformStackForMod(heldItem, modLook);\n }\n }\n\n //Updating item\n if(newStack != heldItem && !ItemStack.areItemsEqual(newStack, heldItem)) {\n playerSP.inventory.setInventorySlotContents(ConfigHandler.offhandTransform ? playerSP.inventory.getSizeInventory() - 1 : playerSP.inventory.currentItem, newStack);\n Omniwand.network.sendToServer(new MessageWandTransform(newStack, playerSP.inventory.currentItem));\n Omniwand.proxy.updateEquippedItem();\n }\n }\n }\n}" } ]
import com.invadermonky.omniwand.client.GuiWand; import com.invadermonky.omniwand.handlers.ConfigHandler; import com.invadermonky.omniwand.handlers.MouseEventOW; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
4,060
package com.invadermonky.omniwand.proxy; public class ClientProxy extends CommonProxy { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event);
package com.invadermonky.omniwand.proxy; public class ClientProxy extends CommonProxy { @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event);
MinecraftForge.EVENT_BUS.register(MouseEventOW.INSTANCE);
2
2023-10-16 00:48:26+00:00
8k
hmcts/opal-fines-service
src/main/java/uk/gov/hmcts/opal/repository/jpa/DefendantAccountSpecs.java
[ { "identifier": "AccountSearchDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java", "snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Company Name or A/C number. */\n private String surname;\n /** Can be either Defendant, Minor Creditor or Company. */\n private String searchType;\n /** Defendant Forenames. */\n private String forename;\n /** Defendant Initials. */\n private String initials;\n /** Defendant Date of Birth. */\n private DateDto dateOfBirth;\n /** Defendant Address, typically just first line. */\n private String addressLineOne;\n /** National Insurance Number. */\n private String niNumber;\n /** Prosecutor Case Reference. */\n private String pcr;\n /** Major Creditor account selection. */\n private String majorCreditor;\n /** Unsure. */\n private String tillNumber;\n}" }, { "identifier": "DateDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/DateDto.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Jacksonized\npublic class DateDto {\n private Integer dayOfMonth;\n private Integer monthOfYear;\n private Integer year;\n\n public static DateDto fromLocalDate(LocalDate local) {\n return DateDto.builder()\n .year(local.getYear())\n .monthOfYear(local.getMonthValue())\n .dayOfMonth(local.getDayOfMonth())\n .build();\n }\n\n public LocalDate toLocalDate() {\n if (year != null) {\n Integer month = Optional.ofNullable(monthOfYear).filter(inRange(1, 12)).orElse(null);\n if (month != null) {\n int high = switch (month) {\n case 2 -> 29;\n case 4, 6, 9, 11 -> 30;\n default -> 31;\n };\n Integer day = Optional.ofNullable(dayOfMonth).filter(inRange(1, high)).orElse(null);\n if (day != null) {\n return LocalDate.of(year, month, day);\n }\n }\n }\n return null;\n }\n\n private Predicate<Integer> inRange(int low, int high) {\n return i -> (i >= low && i <= high);\n }\n}" }, { "identifier": "CourtsEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/CourtsEntity.java", "snippet": "@Data\n@Entity\n@EqualsAndHashCode(callSuper = true)\n@Table(name = \"courts\")\npublic class CourtsEntity extends EnforcersCourtsBaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"court_id\")\n private Long courtId;\n\n @Column(name = \"court_code\", nullable = false)\n private Short courtCode;\n\n @Column(name = \"parent_court_id\")\n private Long parentCourtId;\n\n @Column(name = \"local_justice_area_id\", nullable = false)\n private Short localJusticeAreaId;\n\n @Column(name = \"national_court_code\", length = 7)\n private String nationalCourtCode;\n\n}" }, { "identifier": "DefendantAccountEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountEntity.java", "snippet": "@Entity\n@Data\n@Table(name = \"defendant_accounts\")\npublic class DefendantAccountEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"defendant_account_id_seq\")\n @SequenceGenerator(name = \"defendant_account_id_seq\", sequenceName = \"defendant_account_id_seq\", allocationSize = 1)\n @Column(name = \"defendant_account_id\")\n private Long defendantAccountId;\n\n @ManyToOne\n @JoinColumn(name = \"business_unit_id\", referencedColumnName = \"business_unit_id\", nullable = false)\n private BusinessUnitsEntity businessUnitId;\n\n @Column(name = \"account_number\", length = 20)\n private String accountNumber;\n\n @Column(name = \"imposed_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate imposedHearingDate;\n\n @Column(name = \"imposing_court_id\")\n private Long imposingCourtId;\n\n @Column(name = \"amount_imposed\", precision = 18, scale = 2)\n private BigDecimal amountImposed;\n\n @Column(name = \"amount_paid\", precision = 18, scale = 2)\n private BigDecimal amountPaid;\n\n @Column(name = \"account_balance\", precision = 18, scale = 2)\n private BigDecimal accountBalance;\n\n @Column(name = \"account_status\", length = 2)\n private String accountStatus;\n\n @Column(name = \"completed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate completedDate;\n\n @ManyToOne\n @JoinColumn(name = \"enforcing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity enforcingCourtId;\n\n @ManyToOne\n @JoinColumn(name = \"last_hearing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity lastHearingCourtId;\n\n @Column(name = \"last_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastHearingDate;\n\n @Column(name = \"last_movement_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastMovementDate;\n\n @Column(name = \"last_enforcement\", length = 6)\n private String lastEnforcement;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastChangedDate;\n\n @Column(name = \"originator_name\", length = 100)\n private String originatorName;\n\n @Column(name = \"originator_reference\", length = 40)\n private String originatorReference;\n\n @Column(name = \"originator_type\", length = 10)\n private String originatorType;\n\n @Column(name = \"allow_writeoffs\")\n private boolean allowWriteoffs;\n\n @Column(name = \"allow_cheques\")\n private boolean allowCheques;\n\n @Column(name = \"cheque_clearance_period\")\n private Short chequeClearancePeriod;\n\n @Column(name = \"credit_trans_clearance_period\")\n private Short creditTransferClearancePeriod;\n\n @Column(name = \"enf_override_result_id\", length = 10)\n private String enforcementOverrideResultId;\n\n @Column(name = \"enf_override_enforcer_id\")\n private Long enforcementOverrideEnforcerId;\n\n @Column(name = \"enf_override_tfo_lja_id\")\n private Short enforcementOverrideTfoLjaId;\n\n @Column(name = \"unit_fine_detail\", length = 100)\n private String unitFineDetail;\n\n @Column(name = \"unit_fine_value\", precision = 18, scale = 2)\n private BigDecimal unitFineValue;\n\n @Column(name = \"collection_order\")\n private boolean collectionOrder;\n\n @Column(name = \"collection_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate collectionOrderEffectiveDate;\n\n @Column(name = \"further_steps_notice_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate furtherStepsNoticeDate;\n\n @Column(name = \"confiscation_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate confiscationOrderDate;\n\n @Column(name = \"fine_registration_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate fineRegistrationDate;\n\n @Column(name = \"consolidated_account_type\", length = 1)\n private String consolidatedAccountType;\n\n @Column(name = \"payment_card_requested\")\n private boolean paymentCardRequested;\n\n @Column(name = \"payment_card_requested_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate paymentCardRequestedDate;\n\n @Column(name = \"payment_card_requested_by\", length = 20)\n private String paymentCardRequestedBy;\n\n @Column(name = \"prosecutor_case_reference\", length = 40)\n private String prosecutorCaseReference;\n\n @Column(name = \"enforcement_case_status\", length = 10)\n private String enforcementCaseStatus;\n\n @OneToMany(mappedBy = \"defendantAccount\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> parties;\n\n}" }, { "identifier": "DefendantAccountPartiesEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountPartiesEntity.java", "snippet": "@Entity\n@Table(name = \"defendant_account_parties\")\n@Data\npublic class DefendantAccountPartiesEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"defendant_account_party_id_seq\")\n @SequenceGenerator(name = \"defendant_account_party_id_seq\", sequenceName = \"defendant_account_party_id_seq\",\n allocationSize = 1)\n @Column(name = \"defendant_account_party_id\")\n private Long defendantAccountPartyId;\n\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n @JoinColumn(name = \"defendant_account_id\", nullable = false)\n private DefendantAccountEntity defendantAccount;\n\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n @JoinColumn(name = \"party_id\", nullable = false)\n private PartyEntity party;\n\n @Column(name = \"association_type\", nullable = false, length = 30)\n private String associationType;\n\n @Column(name = \"debtor\", nullable = false)\n private Boolean debtor;\n}" }, { "identifier": "PartyEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/PartyEntity.java", "snippet": "@Entity\n@Data\n@Table(name = \"parties\")\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class PartyEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"party_id_seq\")\n @SequenceGenerator(name = \"party_id_seq\", sequenceName = \"party_id_seq\", allocationSize = 1)\n @Column(name = \"party_id\")\n private Long partyId;\n\n @Column(name = \"organisation\")\n private boolean organisation;\n\n @Column(name = \"organisation_name\", length = 80)\n private String organisationName;\n\n @Column(name = \"surname\", length = 50)\n private String surname;\n\n @Column(name = \"forenames\", length = 50)\n private String forenames;\n\n @Column(name = \"initials\", length = 2)\n private String initials;\n\n @Column(name = \"title\", length = 20)\n private String title;\n\n @Column(name = \"address_line_1\", length = 35)\n private String addressLine1;\n\n @Column(name = \"address_line_2\", length = 35)\n private String addressLine2;\n\n @Column(name = \"address_line_3\", length = 35)\n private String addressLine3;\n\n @Column(name = \"address_line_4\", length = 35)\n private String addressLine4;\n\n @Column(name = \"address_line_5\", length = 35)\n private String addressLine5;\n\n @Column(name = \"postcode\", length = 10)\n private String postcode;\n\n @Column(name = \"account_type\", length = 20)\n private String accountType;\n\n @Column(name = \"birth_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate dateOfBirth;\n\n @Column(name = \"age\")\n private Short age;\n\n @Column(name = \"national_insurance_number\", length = 20)\n private String niNumber;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastChangedDate;\n\n @OneToMany(mappedBy = \"party\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> defendantAccounts;\n}" } ]
import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.ListJoin; import jakarta.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import uk.gov.hmcts.opal.dto.AccountSearchDto; import uk.gov.hmcts.opal.dto.DateDto; import uk.gov.hmcts.opal.entity.CourtsEntity; import uk.gov.hmcts.opal.entity.CourtsEntity_; import uk.gov.hmcts.opal.entity.DefendantAccountEntity; import uk.gov.hmcts.opal.entity.DefendantAccountEntity_; import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity; import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity_; import uk.gov.hmcts.opal.entity.PartyEntity; import uk.gov.hmcts.opal.entity.PartyEntity_; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
4,244
package uk.gov.hmcts.opal.repository.jpa; public class DefendantAccountSpecs { public static Specification<DefendantAccountEntity> findByAccountSearch(AccountSearchDto accountSearchDto) { return Specification.allOf(specificationList( notBlank(accountSearchDto.getSurname()).map(DefendantAccountSpecs::likeSurname), notBlank(accountSearchDto.getForename()).map(DefendantAccountSpecs::likeForename), notBlank(accountSearchDto.getInitials()).map(DefendantAccountSpecs::likeInitials), notBlank(accountSearchDto.getNiNumber()).map(DefendantAccountSpecs::likeNiNumber), notBlank(accountSearchDto.getAddressLineOne()).map(DefendantAccountSpecs::likeAddressLine1), notNullLocalDate(accountSearchDto.getDateOfBirth()).map(DefendantAccountSpecs::equalsDateOfBirth), Optional.ofNullable(accountSearchDto.getCourt()).filter(s -> s.matches("[0-9]+")).map(Long::parseLong) .map(DefendantAccountSpecs::equalsAnyCourtId) )); } @SafeVarargs public static List<Specification<DefendantAccountEntity>> specificationList( Optional<Specification<DefendantAccountEntity>>... optionalSpecs) { return Arrays.stream(optionalSpecs) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } public static Optional<String> notBlank(String candidate) { return Optional.ofNullable(candidate).filter(s -> !s.isBlank()); } public static Optional<LocalDate> notNullLocalDate(DateDto candidate) { return Optional.ofNullable(candidate).map(DateDto::toLocalDate); } public static Specification<DefendantAccountEntity> equalsAccountNumber(String accountNo) { return (root, query, builder) -> { return builder.equal(root.get(DefendantAccountEntity_.accountNumber), accountNo); }; } public static Specification<DefendantAccountEntity> equalsAnyCourtId(Long courtId) { return Specification.anyOf( equalsImposingCourtId(courtId), equalsEnforcingCourtId(courtId), equalsLastHearingCourtId(courtId)); } public static Specification<DefendantAccountEntity> equalsImposingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(root.get(DefendantAccountEntity_.imposingCourtId), courtId); }; } public static Specification<DefendantAccountEntity> equalsEnforcingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(joinEnforcingCourt(root).get(CourtsEntity_.courtId), courtId); }; } public static Specification<DefendantAccountEntity> equalsLastHearingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(joinLastHearingCourt(root).get(CourtsEntity_.courtId), courtId); }; } public static Specification<DefendantAccountEntity> likeSurname(String surname) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.surname), "%" + surname + "%"); }; } public static Specification<DefendantAccountEntity> likeForename(String forename) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.forenames), "%" + forename + "%"); }; } public static Specification<DefendantAccountEntity> likeOrganisationName(String organisation) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.organisationName), "%" + organisation + "%"); }; } public static Specification<DefendantAccountEntity> equalsDateOfBirth(LocalDate dob) { return (root, query, builder) -> { return builder.equal(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.dateOfBirth), dob); }; } public static Specification<DefendantAccountEntity> likeNiNumber(String niNumber) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.niNumber), "%" + niNumber + "%"); }; } public static Specification<DefendantAccountEntity> likeAddressLine1(String addressLine) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.addressLine1), "%" + addressLine + "%"); }; } public static Specification<DefendantAccountEntity> likeInitials(String initials) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.initials), "%" + initials + "%"); }; } public static Join<DefendantAccountEntity, CourtsEntity> joinEnforcingCourt(Root<DefendantAccountEntity> root) { return root.join(DefendantAccountEntity_.enforcingCourtId); } public static Join<DefendantAccountEntity, CourtsEntity> joinLastHearingCourt(Root<DefendantAccountEntity> root) { return root.join(DefendantAccountEntity_.lastHearingCourtId); }
package uk.gov.hmcts.opal.repository.jpa; public class DefendantAccountSpecs { public static Specification<DefendantAccountEntity> findByAccountSearch(AccountSearchDto accountSearchDto) { return Specification.allOf(specificationList( notBlank(accountSearchDto.getSurname()).map(DefendantAccountSpecs::likeSurname), notBlank(accountSearchDto.getForename()).map(DefendantAccountSpecs::likeForename), notBlank(accountSearchDto.getInitials()).map(DefendantAccountSpecs::likeInitials), notBlank(accountSearchDto.getNiNumber()).map(DefendantAccountSpecs::likeNiNumber), notBlank(accountSearchDto.getAddressLineOne()).map(DefendantAccountSpecs::likeAddressLine1), notNullLocalDate(accountSearchDto.getDateOfBirth()).map(DefendantAccountSpecs::equalsDateOfBirth), Optional.ofNullable(accountSearchDto.getCourt()).filter(s -> s.matches("[0-9]+")).map(Long::parseLong) .map(DefendantAccountSpecs::equalsAnyCourtId) )); } @SafeVarargs public static List<Specification<DefendantAccountEntity>> specificationList( Optional<Specification<DefendantAccountEntity>>... optionalSpecs) { return Arrays.stream(optionalSpecs) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } public static Optional<String> notBlank(String candidate) { return Optional.ofNullable(candidate).filter(s -> !s.isBlank()); } public static Optional<LocalDate> notNullLocalDate(DateDto candidate) { return Optional.ofNullable(candidate).map(DateDto::toLocalDate); } public static Specification<DefendantAccountEntity> equalsAccountNumber(String accountNo) { return (root, query, builder) -> { return builder.equal(root.get(DefendantAccountEntity_.accountNumber), accountNo); }; } public static Specification<DefendantAccountEntity> equalsAnyCourtId(Long courtId) { return Specification.anyOf( equalsImposingCourtId(courtId), equalsEnforcingCourtId(courtId), equalsLastHearingCourtId(courtId)); } public static Specification<DefendantAccountEntity> equalsImposingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(root.get(DefendantAccountEntity_.imposingCourtId), courtId); }; } public static Specification<DefendantAccountEntity> equalsEnforcingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(joinEnforcingCourt(root).get(CourtsEntity_.courtId), courtId); }; } public static Specification<DefendantAccountEntity> equalsLastHearingCourtId(Long courtId) { return (root, query, builder) -> { return builder.equal(joinLastHearingCourt(root).get(CourtsEntity_.courtId), courtId); }; } public static Specification<DefendantAccountEntity> likeSurname(String surname) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.surname), "%" + surname + "%"); }; } public static Specification<DefendantAccountEntity> likeForename(String forename) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.forenames), "%" + forename + "%"); }; } public static Specification<DefendantAccountEntity> likeOrganisationName(String organisation) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.organisationName), "%" + organisation + "%"); }; } public static Specification<DefendantAccountEntity> equalsDateOfBirth(LocalDate dob) { return (root, query, builder) -> { return builder.equal(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.dateOfBirth), dob); }; } public static Specification<DefendantAccountEntity> likeNiNumber(String niNumber) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.niNumber), "%" + niNumber + "%"); }; } public static Specification<DefendantAccountEntity> likeAddressLine1(String addressLine) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.addressLine1), "%" + addressLine + "%"); }; } public static Specification<DefendantAccountEntity> likeInitials(String initials) { return (root, query, builder) -> { return builder.like(joinPartyOnAssociationType(root, builder, "Defendant") .get(PartyEntity_.initials), "%" + initials + "%"); }; } public static Join<DefendantAccountEntity, CourtsEntity> joinEnforcingCourt(Root<DefendantAccountEntity> root) { return root.join(DefendantAccountEntity_.enforcingCourtId); } public static Join<DefendantAccountEntity, CourtsEntity> joinLastHearingCourt(Root<DefendantAccountEntity> root) { return root.join(DefendantAccountEntity_.lastHearingCourtId); }
public static Join<DefendantAccountPartiesEntity, PartyEntity> joinPartyOnAssociationType(
4
2023-10-23 14:12:11+00:00
8k
IronRiders/MockSeason23-24
src/main/java/org/ironriders/robot/RobotContainer.java
[ { "identifier": "DriveCommands", "path": "src/main/java/org/ironriders/commands/DriveCommands.java", "snippet": "public class DriveCommands {\n private final DriveSubsystem drive;\n private final SwerveDrive swerve;\n private final VisionSubsystem vision;\n\n public DriveCommands(DriveSubsystem drive) {\n this.drive = drive;\n this.vision = drive.getVision();\n this.swerve = drive.getSwerveDrive();\n }\n\n /**\n * Creates a teleoperated command for swerve drive using joystick inputs.\n *\n * @param x The x-axis joystick input.\n * @param y The y-axis joystick input.\n * @param a The rotation joystick input.\n * @return a command to control the swerve drive during teleop.\n */\n public Command teleopCommand(DoubleSupplier x, DoubleSupplier y, DoubleSupplier a) {\n return drive(\n () -> swerve.getSwerveController().getTargetSpeeds(\n x.getAsDouble(),\n y.getAsDouble(),\n a.getAsDouble() * 2 + swerve.getYaw().getRadians(),\n swerve.getYaw().getRadians(),\n MAX_SPEED\n )\n );\n }\n\n /**\n * Creates a command to set the gyro orientation to a specified rotation.\n *\n * @param rotation The desired rotation for the gyro.\n * @return A command to set the gyro orientation.\n */\n public Command setGyro(Pose2d rotation) {\n return drive.runOnce(() -> swerve.resetOdometry(rotation));\n }\n\n /**\n * Creates a command to drive the swerve robot using specified speeds. Must be repeated to work.\n *\n * @param speeds The supplier providing the desired chassis speeds.\n * @return A command to drive the swerve robot with the specified speeds.\n */\n public Command drive(Supplier<ChassisSpeeds> speeds) {\n return drive(speeds, true, false);\n }\n\n /**\n * Creates a command to drive the swerve robot using specified speeds and control options. Must be repeated to\n * work.\n *\n * @param speeds The supplier providing the desired chassis speeds.\n * @param fieldCentric Whether the control is field-centric.\n * @param openLoop Whether the control is open loop.\n * @return A command to drive the swerve robot with the specified speeds and control options.\n */\n public Command drive(Supplier<ChassisSpeeds> speeds, boolean fieldCentric, boolean openLoop) {\n return drive.runOnce(() -> swerve.drive(\n SwerveController.getTranslation2d(speeds.get()),\n speeds.get().omegaRadiansPerSecond,\n fieldCentric,\n openLoop\n ));\n }\n\n /**\n * Generates a path to the specified destination using default settings false for velocity control which will stop\n * the robot abruptly when it reaches the target.\n *\n * @param target The destination pose represented by a Pose2d object.\n * @return A Command object representing the generated path to the destination.\n */\n public Command pathFindTo(Pose2d target) {\n return pathFindTo(target, false);\n }\n\n /**\n * Generates a path to the specified destination with options for velocity control.\n *\n * @param target The destination pose represented by a Pose2d object.\n * @param preserveEndVelocity A boolean flag indicating whether to preserve velocity at the end of the path.\n * If true, the path will end with the robot going the max velocity; if false, it will\n * stop abruptly.\n * @return A Command object representing the generated path to the destination.\n */\n public Command pathFindTo(Pose2d target, boolean preserveEndVelocity) {\n return AutoBuilder.pathfindToPose(\n target,\n drive.getPathfindingConstraint().getConstraints(),\n preserveEndVelocity ? drive.getPathfindingConstraint().getConstraints().getMaxVelocityMps() : 0\n );\n }\n\n public Command pathFindToTag(Supplier<Integer> id) {\n return pathFindToTag(id, -Arm.LENGTH_FROM_ORIGIN);\n }\n\n /**\n * Generates a path to a specified target identified by a vision tag. This will run only if the id is provided if\n * the id is not provided it will return Command that does nothing and immediately closes itself.\n *\n * @param id The identifier of the vision tag.\n * @param offset The transformation to be applied to the identified target's pose.\n * @return A Command object representing the generated path to the identified target.\n */\n public Command pathFindToTag(Supplier<Integer> id, double offset) {\n Optional<Pose3d> pose = vision.getTag(id.get());\n if (pose.isEmpty()) {\n return Commands.none();\n }\n\n return useVisionForPoseEstimation(\n pathFindTo(Utils.accountedPose(pose.get().toPose2d(), offset).plus(\n new Transform2d(new Translation2d(), Rotation2d.fromDegrees(180))\n ))\n );\n }\n\n public Command lockPose() {\n return drive.runOnce(swerve::lockPose);\n }\n\n /**\n * A utility method that temporarily enables vision-based pose estimation, executes a specified command,\n * and then disables vision-based pose estimation again.\n *\n * @param command The Command object to be executed after enabling vision-based pose estimation.\n * @return A new Command object representing the sequence of actions including vision-based pose estimation.\n */\n public Command useVisionForPoseEstimation(Command command) {\n return vision\n .runOnce(() -> vision.useVisionForPoseEstimation(true))\n .andThen(command)\n .finallyDo(() -> vision.useVisionForPoseEstimation(false));\n }\n\n public Command resetOdometry() {\n return resetOdometry(new Pose2d());\n }\n\n public Command resetOdometry(Pose2d pose) {\n return drive.runOnce(() -> drive.getSwerveDrive().resetOdometry(pose));\n }\n}" }, { "identifier": "RobotCommands", "path": "src/main/java/org/ironriders/commands/RobotCommands.java", "snippet": "public class RobotCommands {\n private final ArmCommands arm;\n private final DriveCommands drive;\n private final DriveSubsystem driveSubsystem;\n private final VisionSubsystem vision;\n private final ManipulatorCommands manipulator;\n\n public RobotCommands(ArmSubsystem arm, DriveSubsystem drive, ManipulatorSubsystem manipulator) {\n this.arm = arm.getCommands();\n this.drive = drive.getCommands();\n driveSubsystem = drive;\n vision = drive.getVision();\n this.manipulator = manipulator.getCommands();\n\n NamedCommands.registerCommand(\"Resting\", resting());\n NamedCommands.registerCommand(\"Driving\", driving());\n NamedCommands.registerCommand(\"Ground Pickup\", groundPickup());\n NamedCommands.registerCommand(\"Exchange\", exchange());\n NamedCommands.registerCommand(\"Exchange Return\", exchangeReturn());\n NamedCommands.registerCommand(\"Portal\", portal());\n NamedCommands.registerCommand(\"Switch\", switchDropOff());\n }\n\n public Command resting() {\n return arm\n .setPivot(Arm.State.REST)\n .alongWith(manipulator.set(Manipulator.State.STOP));\n }\n\n public Command driving() {\n return arm\n .setPivot(Arm.State.FULL)\n .andThen(manipulator.set(Manipulator.State.STOP));\n }\n\n public Command groundPickup() {\n return resting().andThen(manipulator.grabAndStop(3));\n }\n\n public Command exchange() {\n return Commands.sequence(\n driveTo(AprilTagLocation.EXCHANGE),\n arm.setPivot(Arm.State.EXCHANGE),\n manipulator.set(Manipulator.State.EJECT)\n );\n }\n\n public Command exchangeReturn() {\n return Commands.sequence(\n arm.setPivot(Arm.State.EXCHANGE),\n driveTo(AprilTagLocation.EXCHANGE),\n manipulator.grabAndStop(3)\n );\n }\n\n public Command portal() {\n return Commands.sequence(\n driveTo(AprilTagLocation.PORTAL),\n arm.setPivot(Arm.State.PORTAL),\n manipulator.grabAndStop(3)\n );\n }\n\n public Command switchDropOff() {\n return Commands.sequence(\n driveTo(AprilTagLocation.SWITCH),\n arm.setPivot(Arm.State.SWITCH),\n manipulator.set(Manipulator.State.EJECT)\n );\n }\n\n private Command driveTo(AprilTagLocation location) {\n return Commands.sequence(\n drive.lockPose(),\n arm.setPivot(Arm.State.REST),\n Commands.waitSeconds(WAIT_TIME),\n Commands.defer(() -> drive.pathFindToTag(() -> vision.bestTagFor(location)), Set.of(driveSubsystem)),\n drive.lockPose()\n );\n }\n\n /**\n * Builds an autonomous command based on the provided {@code AutoConfig}.\n *\n * @param auto The configuration object specifying the autonomous routine.\n * @return A command representing the autonomous routine specified by the {@code AutoConfig}.\n */\n public Command buildAuto(String auto) {\n return AutoBuilder.buildAuto(auto);\n }\n}" }, { "identifier": "Ports", "path": "src/main/java/org/ironriders/constants/Ports.java", "snippet": "public class Ports {\n /**\n * Driver station ports for the MOTORs.\n */\n public static class Controllers {\n public static final int PRIMARY_CONTROLLER = 0;\n public static final int SECONDARY_CONTROLLER = 1;\n }\n\n /**\n * Ports for each addressable LED strip.\n * <p>\n * S = Strip\n */\n public static class Lights {\n public static class S1 {\n public static final int RSL = 0;\n }\n }\n\n public static class Arm {\n public static final int RIGHT_MOTOR = 10;\n public static final int LEFT_MOTOR = 11;\n\n public static final int PRIMARY_ENCODER = 0;\n public static final int SECONDARY_ENCODER = 1;\n }\n\n public static class Manipulator {\n public static final int RIGHT_MOTOR = 12;\n public static final int LEFT_MOTOR = 13;\n\n }\n}" }, { "identifier": "Teleop", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public class Teleop {\n public static class Speed {\n public static final double MIN_MULTIPLIER = 0.35;\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.1;\n }\n\n public static class Controllers {\n public static class Joystick {\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.15;\n }\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/org/ironriders/lib/Utils.java", "snippet": "public class Utils {\n /**\n * Calculates the absolute error between the target and current values, considering rotational values.\n *\n * @param target The target value.\n * @param current The current value.\n * @return The absolute error between the target and current values.\n */\n public static double rotationalError(double target, double current) {\n double error = Utils.absoluteRotation(target) - current;\n if (error > 180) {\n error -= 360;\n } else if (error < -180) {\n error += 360;\n }\n return error;\n }\n\n /**\n * Normalizes a rotational input value to the range [0, 360) degrees.\n *\n * @param input The input rotational value.\n * @return The normalized rotational value within the range [0, 360) degrees.\n */\n public static double absoluteRotation(double input) {\n return (input % 360 + 360) % 360;\n }\n\n /**\n * Adjusts a given Transform2d by applying a translation offset, considering the rotation of the origin.\n * The offset is modified based on the alliance obtained from DriverStation.getAlliance(). Also rotates by 180.\n *\n * @param origin The original Transform2d to be adjusted.\n * @param offset The translation offset to be applied.\n * @return A new Transform2d representing the adjusted position.\n */\n public static Pose2d accountedPose(Pose2d origin, double offset) {\n double angle = origin.getRotation().getRadians();\n\n return origin.plus(\n new Transform2d(\n new Translation2d(offset * Math.cos(angle), offset * Math.sin(angle)),\n new Rotation2d()\n )\n );\n }\n\n /**\n * Checks if the input value is within a specified tolerance of the target value.\n *\n * @param input The input value.\n * @param target The target value.\n * @param tolerance The allowable tolerance range.\n * @return {@code true} if the input value is within the specified tolerance of the target value, {@code false}\n * otherwise.\n */\n public static boolean isWithinTolerance(double input, double target, double tolerance) {\n return Math.abs(input - target) <= tolerance;\n }\n\n /**\n * Applies deadband to the input value. If the input falls within the specified deadband range, it is set to 0.\n *\n * @param input The input value to be processed.\n * @param deadband The range around 0 within which the output is set to 0.\n * @return The processed output value after applying deadband.\n */\n public static double deadband(double input, double deadband) {\n return isWithinTolerance(input, 0, deadband) ? 0 : input;\n }\n\n /**\n * Applies a control curve to the input value based on the specified exponent and deadband.\n * The control curve modifies the input such that values within the deadband are set to 0,\n * and the remaining values are transformed using an exponent function.\n *\n * @param input The input value to be modified by the control curve.\n * @param exponent The exponent to which the normalized input (after deadband removal) is raised.\n * @param deadband The range around 0 within which the output is set to 0.\n * @return The modified output value after applying the control curve.\n */\n public static double controlCurve(double input, double exponent, double deadband) {\n input = deadband(input, deadband);\n if (input == 0) {\n return 0;\n }\n\n return sign(input) * Math.pow((Math.abs(input) - deadband) / (1 - deadband), exponent);\n }\n\n /**\n * Returns the sign of the input value.\n *\n * @param input The input value to determine the sign.\n * @return 1 if the input is positive, -1 if negative, 0 if zero.\n */\n public static double sign(double input) {\n return input > 0 ? 1 : -1;\n }\n}" }, { "identifier": "ArmSubsystem", "path": "src/main/java/org/ironriders/subsystems/ArmSubsystem.java", "snippet": "public class ArmSubsystem extends SubsystemBase {\n private final ArmCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Arm.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Arm.LEFT_MOTOR, kBrushless);\n private final DutyCycleEncoder primaryEncoder = new DutyCycleEncoder(Ports.Arm.PRIMARY_ENCODER);\n private final DutyCycleEncoder secondaryEncoder = new DutyCycleEncoder(Ports.Arm.SECONDARY_ENCODER);\n private final ProfiledPIDController pid = new ProfiledPIDController(P, I, D, PROFILE);\n\n public ArmSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n\n leader.setIdleMode(kCoast);\n follower.setIdleMode(kCoast);\n\n primaryEncoder.setPositionOffset(PRIMARY_ENCODER_OFFSET);\n primaryEncoder.setDistancePerRotation(360);\n secondaryEncoder.setPositionOffset(SECONDARY_ENCODER_OFFSET);\n secondaryEncoder.setDistancePerRotation(360);\n\n leader.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n leader.getEncoder().setPosition(getPrimaryPosition());\n\n follower.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n follower.getEncoder().setPosition(getPrimaryPosition());\n\n leader.setSoftLimit(kReverse, Limit.REVERSE);\n leader.enableSoftLimit(kReverse, true);\n leader.setSoftLimit(kForward, Limit.FORWARD);\n leader.enableSoftLimit(kForward, true);\n follower.setSoftLimit(kReverse, Limit.REVERSE);\n follower.enableSoftLimit(kReverse, true);\n follower.setSoftLimit(kForward, Limit.FORWARD);\n follower.enableSoftLimit(kForward, true);\n\n follower.follow(leader, true);\n resetPID();\n\n SmartDashboard.putData(\"arm/Arm PID\", pid);\n SmartDashboard.putData(\"arm/Leader\", primaryEncoder);\n SmartDashboard.putData(\"arm/Follower\", secondaryEncoder);\n\n commands = new ArmCommands(this);\n }\n\n @Override\n public void periodic() {\n SmartDashboard.putNumber(\"arm/Leader (integrated)\", leader.getEncoder().getPosition());\n SmartDashboard.putNumber(\"arm/Follower (integrated)\", follower.getEncoder().getPosition());\n\n if (!Utils.isWithinTolerance(getPrimaryPosition(), getSecondaryPosition(), FAILSAFE_DIFFERENCE)) {\n leader.set(0);\n return;\n }\n\n leader.set(pid.calculate(getPosition()));\n }\n\n\n public ArmCommands getCommands() {\n return commands;\n }\n\n public double getPrimaryPosition() {\n return primaryEncoder.getDistance() + PRIMARY_ENCODER_OFFSET;\n }\n\n public double getSecondaryPosition() {\n return -(secondaryEncoder.getDistance() + SECONDARY_ENCODER_OFFSET);\n }\n\n /**\n * In degrees.\n */\n public double getPosition() {\n return getPrimaryPosition();\n }\n\n public void set(double target) {\n pid.setGoal(target);\n }\n\n public void resetPID() {\n pid.reset(getPosition());\n pid.setGoal(getPosition());\n }\n}" }, { "identifier": "DriveSubsystem", "path": "src/main/java/org/ironriders/subsystems/DriveSubsystem.java", "snippet": "public class DriveSubsystem extends SubsystemBase {\n private final DriveCommands commands;\n private final VisionSubsystem vision = new VisionSubsystem();\n private final SwerveDrive swerveDrive;\n private final EnumSendableChooser<PathfindingConstraintProfile> constraintProfile = new EnumSendableChooser<>(\n PathfindingConstraintProfile.class,\n PathfindingConstraintProfile.getDefault(),\n \"auto/Pathfinding Constraint Profile\"\n );\n\n public DriveSubsystem() {\n try {\n swerveDrive = new SwerveParser(\n new File(Filesystem.getDeployDirectory(), Drive.SWERVE_CONFIG_LOCATION)\n ).createSwerveDrive(MAX_SPEED, STEERING_CONVERSION_FACTOR, DRIVE_CONVERSION_FACTOR);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n SwerveDriveTelemetry.verbosity = SwerveDriveTelemetry.TelemetryVerbosity.HIGH;\n\n AutoBuilder.configureHolonomic(\n swerveDrive::getPose,\n swerveDrive::resetOdometry,\n swerveDrive::getRobotVelocity,\n swerveDrive::setChassisSpeeds,\n new HolonomicPathFollowerConfig(\n 4.5,\n Dimensions.DRIVEBASE_RADIUS,\n new ReplanningConfig()\n ),\n () -> DriverStation.getAlliance().orElse(Alliance.Blue).equals(Alliance.Red),\n this\n );\n\n commands = new DriveCommands(this);\n }\n\n @Override\n public void periodic() {\n PathPlannerLogging.setLogActivePathCallback((poses) -> {\n List<Trajectory.State> states = new ArrayList<>();\n for (Pose2d pose : poses) {\n Trajectory.State state = new Trajectory.State();\n state.poseMeters = pose;\n states.add(state);\n }\n\n swerveDrive.postTrajectory(new Trajectory(states));\n });\n\n getVision().getPoseEstimate().ifPresent(estimatedRobotPose -> {\n swerveDrive.resetOdometry(estimatedRobotPose.estimatedPose.toPose2d());\n swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n// swerveDrive.addVisionMeasurement(\n// estimatedRobotPose.estimatedPose.toPose2d(),\n// estimatedRobotPose.timestampSeconds\n// );\n// swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n });\n }\n\n public DriveCommands getCommands() {\n return commands;\n }\n\n public void setGyro(Rotation3d rotation) {\n swerveDrive.setGyro(new Rotation3d());\n }\n\n public VisionSubsystem getVision() {\n return vision;\n }\n\n public PathfindingConstraintProfile getPathfindingConstraint() {\n return constraintProfile.getSelected();\n }\n\n public SwerveDrive getSwerveDrive() {\n return swerveDrive;\n }\n}" }, { "identifier": "ManipulatorSubsystem", "path": "src/main/java/org/ironriders/subsystems/ManipulatorSubsystem.java", "snippet": "public class ManipulatorSubsystem extends SubsystemBase {\n private final ManipulatorCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Manipulator.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Manipulator.LEFT_MOTOR, kBrushless);\n\n public ManipulatorSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n leader.setIdleMode(kBrake);\n follower.setIdleMode(kBrake);\n\n follower.follow(leader, true);\n\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n\n commands = new ManipulatorCommands(this);\n }\n\n public ManipulatorCommands getCommands() {\n return commands;\n }\n\n public void set(State state) {\n switch (state) {\n case GRAB -> grab();\n case EJECT -> eject();\n case STOP -> stop();\n }\n }\n\n private void grab() {\n SmartDashboard.putString(\"manipulator/State\", \"GRAB\");\n leader.set(-GRAB_SPEED);\n }\n\n private void eject() {\n SmartDashboard.putString(\"manipulator/State\", \"EJECT\");\n leader.set(EJECT_SPEED);\n }\n\n private void stop() {\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n leader.set(0);\n }\n}" }, { "identifier": "DEFAULT_AUTO", "path": "src/main/java/org/ironriders/constants/Auto.java", "snippet": "public static final String DEFAULT_AUTO = \"TEST\";" }, { "identifier": "Joystick", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static class Joystick {\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.15;\n}" }, { "identifier": "DEADBAND", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static final double DEADBAND = 0.1;" }, { "identifier": "MIN_MULTIPLIER", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static final double MIN_MULTIPLIER = 0.35;" } ]
import com.pathplanner.lib.auto.AutoBuilder; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.button.CommandJoystick; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import org.ironriders.commands.DriveCommands; import org.ironriders.commands.RobotCommands; import org.ironriders.constants.Ports; import org.ironriders.constants.Teleop; import org.ironriders.lib.Utils; import org.ironriders.subsystems.ArmSubsystem; import org.ironriders.subsystems.DriveSubsystem; import org.ironriders.subsystems.ManipulatorSubsystem; import static org.ironriders.constants.Auto.DEFAULT_AUTO; import static org.ironriders.constants.Teleop.Controllers.Joystick; import static org.ironriders.constants.Teleop.Speed.DEADBAND; import static org.ironriders.constants.Teleop.Speed.MIN_MULTIPLIER;
6,095
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.ironriders.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { private final DriveSubsystem drive = new DriveSubsystem(); private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem(); private final ArmSubsystem arm = new ArmSubsystem(); private final CommandXboxController primaryController = new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER); private final CommandJoystick secondaryController = new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER); private final RobotCommands commands = new RobotCommands(arm, drive, manipulator); private final DriveCommands driveCommands = drive.getCommands(); private final SendableChooser<String> autoOptionSelector = new SendableChooser<>(); /** * The container for the robot. Contains subsystems, IO devices, and commands. */ public RobotContainer() { for (String auto : AutoBuilder.getAllAutoNames()) { if (auto.equals("REGISTERED_COMMANDS")) continue; autoOptionSelector.addOption(auto, auto); }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.ironriders.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { private final DriveSubsystem drive = new DriveSubsystem(); private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem(); private final ArmSubsystem arm = new ArmSubsystem(); private final CommandXboxController primaryController = new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER); private final CommandJoystick secondaryController = new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER); private final RobotCommands commands = new RobotCommands(arm, drive, manipulator); private final DriveCommands driveCommands = drive.getCommands(); private final SendableChooser<String> autoOptionSelector = new SendableChooser<>(); /** * The container for the robot. Contains subsystems, IO devices, and commands. */ public RobotContainer() { for (String auto : AutoBuilder.getAllAutoNames()) { if (auto.equals("REGISTERED_COMMANDS")) continue; autoOptionSelector.addOption(auto, auto); }
autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO);
8
2023-10-23 20:31:46+00:00
8k
ChrisGenti/DiscordTickets
src/main/java/com/github/chrisgenti/discordtickets/DiscordTickets.java
[ { "identifier": "CommandListener", "path": "src/main/java/com/github/chrisgenti/discordtickets/listeners/CommandListener.java", "snippet": "public class CommandListener implements SlashCommandCreateListener {\n private final DiscordApi discordAPI;\n private final MongoManager mongoManager;\n private final TicketManager ticketManager;\n\n public CommandListener(DiscordTickets discord) {\n this.discordAPI = discord.getDiscord();\n this.mongoManager = discord.getMongoManager();\n this.ticketManager = discord.getTicketManager();\n }\n\n @Override\n public void onSlashCommandCreate(SlashCommandCreateEvent event) {\n String command = event.getSlashCommandInteraction().getCommandName();\n if (!command.equals(\"message\") && !command.equals(\"close\"))\n return;\n\n if (command.equals(\"message\")) {\n if (!event.getSlashCommandInteraction().getChannel().isPresent())\n return;\n TextChannel channel = event.getSlashCommandInteraction().getChannel().get();\n\n if (!channel.getIdAsString().equals(\"1159103734752759938\")) {\n event.getInteraction().createImmediateResponder()\n .setFlags(MessageFlag.EPHEMERAL)\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"This channel is not enabled for tickets.\")\n .setColor(Color.RED)\n ).respond();\n return;\n }\n\n event.getInteraction().createImmediateResponder()\n .setFlags(MessageFlag.EPHEMERAL)\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"Main message sent successfully.\")\n .setColor(Color.GREEN)\n ).respond();\n this.createMessage().send(channel); return;\n }\n\n if (event.getSlashCommandInteraction().getChannel().isEmpty())\n return;\n TextChannel channel = event.getSlashCommandInteraction().getChannel().get();\n\n if (event.getInteraction().getServer().isEmpty())\n return;\n Server server = event.getInteraction().getServer().get();\n\n if (server.getChannelById(channel.getIdAsString()).isEmpty())\n return;\n ServerChannel serverChannel = server.getChannelById(channel.getIdAsString()).get();\n\n Ticket ticket = ticketManager.getTicketByChannel(serverChannel.getIdAsString());\n if (ticket == null) {\n event.getInteraction().createImmediateResponder()\n .setFlags(MessageFlag.EPHEMERAL)\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"This is not a dedicated ticket channel.\")\n .setColor(Color.RED)\n ).respond();\n return;\n }\n User user = event.getInteraction().getUser(); User userTarget = discordAPI.getUserById(ticket.getUserID()).join();\n\n if (server.getMemberById(ticket.getUserID()).isPresent())\n userTarget = server.getMemberById(ticket.getUserID()).get();\n\n event.getInteraction().createImmediateResponder()\n .setFlags(MessageFlag.EPHEMERAL)\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"You have successfully closed this ticket.\")\n .setColor(Color.GREEN)\n ).respond();\n serverChannel.delete(); ticket.setCloseDate(Date.from(Instant.now())); ticketManager.getTicketCache().remove(ticket); mongoManager.closeTicket(ticket);\n\n userTarget.sendMessage(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets (\" + ticket.getId() + \")\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\n \"\\n\" + \"\\n\" +\n \"**CLOSED BY:** \" + user.getDisplayName(server) + \"\\n\" +\n \"**CLOSED ON:** \" + Util.formatDate(ticket.getCloseDate()) + \"\\n\" + \"\\n\" +\n \"__**NOTE**__ *There will be more updates soon.*\"\n )\n .setThumbnail(\"https://i.imgur.com/s5k4che.png\")\n .setColor(Color.ORANGE)\n ).join();\n\n Logger.info(\n MessageUtil.TICKET_CLOSE_MESSAGE\n .replace(\"%admin_username%\", user.getDisplayName(server))\n .replace(\"%username%\", userTarget.getDisplayName(server))\n .replace(\"%ticket_id%\", ticket.getId() + \"\")\n );\n }\n\n private MessageBuilder createMessage() {\n return new MessageBuilder()\n .setEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\n \"If you're in need of support from a staff member, please create a ticket! You can ask about any issues or questions you may have.\" +\n \"\\n\" + \"\\n\" +\n \"Our staff will try to respond to you as quick as possible! Please refrain from pinging any staff.\"\n )\n .setThumbnail(\"https://i.imgur.com/s5k4che.png\")\n .setColor(Color.ORANGE)\n )\n .addComponents(\n ActionRow.of(SelectMenu.createStringMenu(\"tickets_menu\", \"How can we help?\", Arrays.asList(\n TicketType.PUNISHMENT.createMenuOption(), TicketType.PAYMENTS.createMenuOption(), TicketType.STAFF_REPORTS.createMenuOption(), TicketType.PLAYER_REPORTS.createMenuOption(), TicketType.BUG_REPORTS.createMenuOption(), TicketType.GENERAL_QUESTIONS.createMenuOption()\n )))\n );\n }\n}" }, { "identifier": "MenuListener", "path": "src/main/java/com/github/chrisgenti/discordtickets/listeners/menus/MenuListener.java", "snippet": "public class MenuListener implements SelectMenuChooseListener {\n @Override\n public void onSelectMenuChoose(SelectMenuChooseEvent event) {\n String customID = event.getSelectMenuInteraction().getCustomId();\n if (!customID.equals(\"tickets_menu\"))\n return;\n\n if (event.getSelectMenuInteraction().getChosenOptions().stream().findFirst().isEmpty())\n return;\n String value = event.getSelectMenuInteraction().getChosenOptions().stream().findFirst().get().getValue();\n\n TicketType ticketType = TicketType.getByCustomID(value);\n if (ticketType == null)\n return;\n\n switch (ticketType) {\n case PLAYER_REPORTS:\n event.getInteraction().respondWithModal(value + \"_modal\", ticketType.getLabel() + \" Ticket Model\", Arrays.asList(\n ActionRow.of(\n TextInput.create(TextInputStyle.SHORT, \"username\", \"What is your in-game name?\", true)\n ),\n ActionRow.of(\n TextInput.create(TextInputStyle.SHORT, \"reported_username\", \"What is the staffer's in-game username?\", true)\n ),\n ActionRow.of(\n TextInput.create(TextInputStyle.PARAGRAPH, \"description\", \"What happened? (Explain in detail)\", true)\n )\n ));\n break;\n case STAFF_REPORTS:\n event.getInteraction().respondWithModal(value + \"_modal\", ticketType.getLabel() + \" Ticket Model\", Arrays.asList(\n ActionRow.of(\n TextInput.create(TextInputStyle.SHORT, \"username\", \"What is your in-game name?\", true)\n ),\n ActionRow.of(\n TextInput.create(TextInputStyle.SHORT, \"reported_username\", \"What is the player's in-game username?\", true)\n ),\n ActionRow.of(\n TextInput.create(TextInputStyle.PARAGRAPH, \"description\", \"What happened? (Explain in detail)\", true)\n )\n ));\n break;\n default:\n event.getInteraction().respondWithModal(value + \"_modal\", ticketType.getLabel() + \" Ticket Model\", Arrays.asList(\n ActionRow.of(\n TextInput.create(TextInputStyle.SHORT, \"username\", \"What is your in-game name?\", true)\n ),\n ActionRow.of(\n TextInput.create(TextInputStyle.PARAGRAPH, \"description\", \"What happened? (Explain in detail)\", true)\n )\n ));\n }\n }\n}" }, { "identifier": "ModalListener", "path": "src/main/java/com/github/chrisgenti/discordtickets/listeners/modals/ModalListener.java", "snippet": "public class ModalListener implements ModalSubmitListener {\n private final MongoManager mongoManager;\n private final TicketManager ticketManager;\n\n public ModalListener(DiscordTickets discord) {\n this.mongoManager = discord.getMongoManager();\n this.ticketManager = discord.getTicketManager();\n }\n\n @Override\n public void onModalSubmit(ModalSubmitEvent event) {\n User user = event.getModalInteraction().getUser(); String customID = event.getModalInteraction().getCustomId().replace(\"_modal\", \"\");\n\n TicketType ticketType = TicketType.getByCustomID(customID);\n if (ticketType == null)\n return;\n\n if (event.getModalInteraction().getServer().isEmpty())\n return;\n Server server = event.getModalInteraction().getServer().get();\n\n if (ticketManager.getTicketsByUser(user.getIdAsString()).size() == 2) {\n event.getInteraction().createImmediateResponder()\n .setFlags(MessageFlag.EPHEMERAL)\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(\"Discord Support Tickets\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"You have reached your ticket limit.\")\n .setColor(Color.RED)\n ).respond();\n return;\n }\n\n if (server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().isEmpty())\n return;\n ChannelCategory category = server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().get();\n\n Role role = null;\n if (server.getRolesByName(\"SUPPORT\").stream().findFirst().isPresent())\n role = server.getRolesByName(\"SUPPORT\").stream().findFirst().get();\n\n String username = null;\n if (event.getModalInteraction().getTextInputValueByCustomId(\"username\").isPresent())\n username = event.getModalInteraction().getTextInputValueByCustomId(\"username\").get();\n\n String description = null;\n if (event.getModalInteraction().getTextInputValueByCustomId(\"description\").isPresent())\n description = event.getModalInteraction().getTextInputValueByCustomId(\"description\").get();\n\n String reportedUsername = null;\n if ((ticketType == TicketType.PLAYER_REPORTS || ticketType == TicketType.STAFF_REPORTS) && event.getModalInteraction().getTextInputValueByCustomId(\"reported_username\").isPresent())\n reportedUsername = event.getModalInteraction().getTextInputValueByCustomId(\"reported_username\").get();\n\n int number = ticketManager.getLastNumber() + 1; MessageBuilder builder = reportedUsername == null ? this.createMessage(ticketType, role, username, description) : this.createMessage(ticketType, role, username, reportedUsername, description);\n server.createTextChannelBuilder()\n .setCategory(category)\n .setName(\n \"ticket-{username}-{id}\"\n .replace(\"{username}\", user.getName())\n .replace(\"{id}\", String.valueOf(number))\n )\n .addPermissionOverwrite(server.getEveryoneRole(), new PermissionsBuilder().setDenied(PermissionType.VIEW_CHANNEL).build())\n .addPermissionOverwrite(event.getModalInteraction().getUser(), new PermissionsBuilder().setAllowed(PermissionType.VIEW_CHANNEL, PermissionType.SEND_MESSAGES).build())\n .create().whenComplete((var, throwable) -> {\n if (var.getCurrentCachedInstance().isEmpty())\n return;\n TextChannel channel = var.getCurrentCachedInstance().get();\n\n builder.send(channel);\n event.getInteraction().createImmediateResponder()\n .setAllowedMentions(new AllowedMentionsBuilder().build())\n .addEmbed(\n new EmbedBuilder()\n .setAuthor(ticketType.getLabel() + \" Ticket\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\"New ticket created: <#\" + channel.getIdAsString() + \">\")\n .setColor(Color.GREEN)\n\n ).setFlags(MessageFlag.EPHEMERAL).respond();\n\n Ticket ticket = new Ticket(number, ticketType, user.getIdAsString(), channel.getIdAsString(), Date.from(Instant.now()));\n mongoManager.createTicket(ticket); ticketManager.getTicketCache().add(ticket); ticketManager.setLastNumber(number);\n\n Logger.info(\n MessageUtil.TICKET_CREATE_MESSAGE\n .replace(\"%username%\", user.getDisplayName(server))\n .replace(\"%ticket_category%\", ticketType.getLabel())\n .replace(\"%ticket_id%\", ticket.getId() + \"\")\n );\n });\n }\n\n private MessageBuilder createMessage(TicketType ticketType, Role role, String username, String description) {\n String mentionLine = \"\";\n if (role != null)\n mentionLine = \"**\" + role.getMentionTag() + \"** \\n \\n\";\n\n return new MessageBuilder()\n .setAllowedMentions(\n new AllowedMentionsBuilder()\n .setMentionRoles(true)\n .build()\n )\n .setEmbed(\n new EmbedBuilder()\n .setAuthor(ticketType.getLabel() + \" Ticket\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\n \"**What is your in-game name? **\" + \"\\n\" + username + \"\\n\" + \"\\n\" +\n \"**What happened? **\" + \"\\n\" + description + \"\\n\" + \"\\n\" + mentionLine\n )\n .setFooter(\"\\n\" + \"Thank you for making a support ticket, our staff team will be with you shortly! \")\n .setColor(Color.ORANGE)\n );\n }\n\n private MessageBuilder createMessage(TicketType ticketType, Role role, String username, String reportedUsername, String description) {\n String mentionLine = \"\";\n if (role != null)\n mentionLine = \"**\" + role.getMentionTag() + \"** \\n \\n\";\n\n String line = ticketType == TicketType.STAFF_REPORTS ? \"What is the staffer's in-game username?\" : \"What is the player's in-game username?\";\n return new MessageBuilder()\n .setAllowedMentions(\n new AllowedMentionsBuilder()\n .setMentionRoles(true)\n .build()\n )\n .setEmbed(\n new EmbedBuilder()\n .setAuthor(ticketType.getLabel() + \" Ticket\", \"\", \"https://i.imgur.com/s5k4che.png\")\n .setDescription(\n \"**What is your in-game name? **\" + \"\\n\" + username + \"\\n\" + \"\\n\" +\n \"**\" + line + \"**\" + \"\\n\" + reportedUsername + \"\\n\" + \"\\n\" +\n \"**What happened? **\" + \"\\n\" + description + \"\\n\" + \"\\n\" + mentionLine\n )\n .setFooter(\"\\n\" + \"Thank you for making a support ticket, our staff team will be with you shortly!\")\n .setColor(Color.ORANGE)\n );\n }\n}" }, { "identifier": "TicketManager", "path": "src/main/java/com/github/chrisgenti/discordtickets/managers/TicketManager.java", "snippet": "public class TicketManager {\n private int lastNumber;\n private final List<Ticket> ticketCache;\n\n public TicketManager(DiscordTickets discord) {\n this.ticketCache = new ArrayList<>();\n\n MongoManager mongoManager = discord.getMongoManager();\n this.setLastNumber(mongoManager.ticketLastNumber()); this.ticketCache.addAll(mongoManager.ticketsToList());\n }\n\n public int getLastNumber() {\n return lastNumber;\n }\n\n public Ticket getTicketByChannel(String channelID) {\n return this.ticketCache.stream().filter(var -> var.getChannelID().equals(channelID)).findFirst().orElse(null);\n }\n\n public List<Ticket> getTicketsByUser(String userID) {\n return this.ticketCache.stream().filter(var -> var.getUserID().equals(userID)).collect(Collectors.toList());\n }\n\n public List<Ticket> getTicketCache() {\n return ticketCache;\n }\n\n public void setLastNumber(int number) {\n this.lastNumber = number;\n }\n}" }, { "identifier": "MongoManager", "path": "src/main/java/com/github/chrisgenti/discordtickets/managers/mongo/MongoManager.java", "snippet": "public class MongoManager {\n private final MongoClientSettings settings;\n\n public MongoManager(String hostname, String username, String password) {\n LoggerFactory.getLogger(MongoManager.class);\n\n this.settings = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(\"mongodb+srv://\" + username + \":\" + password + \"@\" + hostname + \"/?retryWrites=true&w=majority\"))\n .serverApi(\n ServerApi.builder()\n .version(ServerApiVersion.V1)\n .build()\n )\n .build();\n }\n\n public void createTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate()));\n collection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public void closeTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> openCollection = database.getCollection(\"opened_tickets\");\n MongoCollection<Document> closeConnection = database.getCollection(\"closed_tickets\");\n\n Document searchDocument = new Document(); searchDocument.put(\"id\", ticket.getId());\n openCollection.deleteOne(searchDocument);\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate())); document.put(\"close_date\", Util.formatDate(ticket.getCloseDate()));\n closeConnection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public int ticketLastNumber() {\n List<Integer> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection;\n\n collection = database.getCollection(\"opened_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n\n collection = database.getCollection(\"closed_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n } catch (MongoException ignored) {}\n }\n return values.isEmpty() ? 0 : Collections.max(values);\n }\n\n public List<Ticket> ticketsToList() {\n List<Ticket> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext()) {\n Document document = cursor.next();\n\n values.add(new Ticket(\n document.getInteger(\"id\"), TicketType.valueOf(document.getString(\"type\")), document.getString(\"user_id\"), document.getString(\"channel_id\"), Util.parseDate(document.getString(\"open_date\"))\n ));\n }\n }\n } catch (MongoException ignored) {}\n }\n return values;\n }\n\n public int openedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n\n public int closedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"closed_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n}" }, { "identifier": "ObjectTriple", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/ObjectTriple.java", "snippet": "public class ObjectTriple<LEFT, MID, RIGHT> {\n private LEFT left;\n private MID mid;\n private RIGHT right;\n\n private ObjectTriple(@Nullable LEFT left, @Nullable MID mid, @Nullable RIGHT right) {\n this.left = left; this.mid = mid; this.right = right;\n }\n\n @SuppressWarnings(\"InstantiationOfUtilityClass\")\n public static <LEFT, MID, RIGHT> ObjectTriple<LEFT, MID, RIGHT> of(\n @Nullable LEFT left, @Nullable MID mid, @Nullable RIGHT right\n ) {\n return new ObjectTriple<>(left, mid, right);\n }\n\n public LEFT left() {\n return left;\n }\n\n public MID mid() {\n return mid;\n }\n\n public RIGHT right() {\n return right;\n }\n}" }, { "identifier": "FileResult", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/enums/files/FileResult.java", "snippet": "public enum FileResult {\n EXISTING(\"loaded from existing file\"),\n CREATED(\"missing file, created a new one\"),\n MALFORMED(\"\");\n\n private final String reason;\n FileResult(String reason) {\n this.reason = reason;\n }\n\n public String reason() {\n return reason;\n }\n}" }, { "identifier": "FileUtil", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/utils/files/FileUtil.java", "snippet": "public class FileUtil {\n private FileUtil() {}\n\n public static @NotNull ObjectTriple<FileResult, DiscordData, Exception> loadData(@NotNull Path path) {\n File var = path.toFile();\n\n ObjectMapper mapper = new ObjectMapper();\n SimpleModule module = new SimpleModule(\"DiscordDataSerializer\");\n\n module.addDeserializer(DiscordData.class, new DiscordDataDeserializer());\n module.addSerializer(DiscordData.class, new DiscordDataSerializer());\n mapper.registerModule(module);\n\n ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());\n ObjectReader reader = mapper.reader();\n\n if (createFileIfNeeded(var)) {\n try {\n DiscordData discordData = new DiscordData(); writer.writeValue(var, new DiscordData());\n return ObjectTriple.of(FileResult.CREATED, discordData, null);\n } catch (IOException exc) {\n throw new RuntimeException(exc);\n }\n }\n\n try {\n DiscordData discordData = reader.readValue(var, DiscordData.class);\n return ObjectTriple.of(FileResult.EXISTING, discordData, null);\n } catch (Exception exc) {\n return ObjectTriple.of(FileResult.MALFORMED, null, exc);\n }\n }\n\n private static boolean createFileIfNeeded(@NotNull File file) {\n try {\n return file.createNewFile();\n } catch (IOException exc) {\n throw new RuntimeException(exc);\n }\n }\n}" }, { "identifier": "MessageUtil", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/utils/messages/MessageUtil.java", "snippet": "public class MessageUtil {\n private static final String RESET = \"\\033[0m\";\n private static final String RED = \"\\033[1;31m\";\n private static final String BLUE = \"\\033[1;34m\";\n private static final String WHITE = \"\\033[0;37m\";\n\n private static final char CUBE = '\\u25A0';\n private static final char ARROW = '\\u25B8';\n\n private static final String CUBE_COMPONENT = BLUE + CUBE;\n private static final String CUBE_COMPONENT_LINE = CUBE_COMPONENT + \" \" + CUBE_COMPONENT + \" \" + CUBE_COMPONENT;\n\n private static final String ARROW_COMPONENT = WHITE + ARROW + \" \";\n\n public static final String LAUNCH_MESSAGE =\n \"Starting Discord Tickets...\" + \"\\n\" + \"\\n\" +\n CUBE_COMPONENT_LINE + \"\\n\" + CUBE_COMPONENT_LINE + \" DISCORD TICKETS v1.0\" + \"\\n\" +\n CUBE_COMPONENT_LINE + \"\\n\" + \"\\n\" +\n ARROW_COMPONENT + \"os: \" + System.getProperty(\"os.name\") + \", \" + System.getProperty(\"os.version\") + \" - \" + System.getProperty(\"os.arch\") + \"\\n\" +\n ARROW_COMPONENT + \"java: \" + System.getProperty(\"java.version\") + \" - \" + System.getProperty(\"java.vendor\") + \", \" + System.getProperty(\"java.vendor.url\") + RESET + \"\\n\";\n\n public static final String CONFIG_MESSAGE =\n \"Discord Tickets launch result...\" + \"\\n\" + \"\\n\" +\n ARROW_COMPONENT + \"config location: config.json, %config_result%\" + \"\\n\" +\n ARROW_COMPONENT + \"opened tickets: %opened_tickets%, closed tickets: %closed_tickets%\" + \"\\n\" + \"\\n\" +\n WHITE +\"Bot started in %mills%s\" + \"\\n\";\n\n public static final String MALFORMED_CONFIG_MESSAGE =\n \"\\n\" + \"\\n\" +\n RED + \" ! Error while launching the Discord Tickets...\" + \"\\n\" +\n RED + \" The configuration file is malformed, for security\" + \"\\n\" +\n RED + \" and logistic reason the server will automatically\" + \"\\n\" +\n RED + \" stop in 5 seconds...\" + \"\\n\" + \"\\n\" + RESET;\n\n public static String TICKET_CREATE_MESSAGE =\n WHITE + \"%username% opened a ticket in the %ticket_category% category.\" + BLUE + \" ID: %ticket_id%\" + RESET;\n\n public static String TICKET_CLOSE_MESSAGE =\n WHITE + \"%admin_username% closed %username%'s ticket.\" + BLUE + \" ID: %ticket_id%\" + RESET;\n}" } ]
import com.github.chrisgenti.discordtickets.listeners.CommandListener; import com.github.chrisgenti.discordtickets.listeners.menus.MenuListener; import com.github.chrisgenti.discordtickets.listeners.modals.ModalListener; import com.github.chrisgenti.discordtickets.managers.TicketManager; import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager; import com.github.chrisgenti.discordtickets.tools.ObjectTriple; import com.github.chrisgenti.discordtickets.tools.enums.files.FileResult; import com.github.chrisgenti.discordtickets.tools.utils.files.FileUtil; import com.github.chrisgenti.discordtickets.tools.utils.messages.MessageUtil; import org.javacord.api.DiscordApi; import org.javacord.api.DiscordApiBuilder; import org.javacord.api.entity.intent.Intent; import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.interaction.SlashCommand; import org.jetbrains.annotations.NotNull; import org.tinylog.Logger; import java.nio.file.Paths; import java.text.DecimalFormat;
6,473
package com.github.chrisgenti.discordtickets; public class DiscordTickets { private final DecimalFormat decimalFormat = new DecimalFormat("##0,000"); private DiscordApi discord; private MongoManager mongoManager; private TicketManager ticketManager; public static final String CONFIG_LOCATION = System.getProperty("config.location", "config.json"); public void init() { /* LAUNCH MESSAGE */ Logger.info(MessageUtil.LAUNCH_MESSAGE); /* LOAD */ this.load(); } private void load() { long mills = System.currentTimeMillis();
package com.github.chrisgenti.discordtickets; public class DiscordTickets { private final DecimalFormat decimalFormat = new DecimalFormat("##0,000"); private DiscordApi discord; private MongoManager mongoManager; private TicketManager ticketManager; public static final String CONFIG_LOCATION = System.getProperty("config.location", "config.json"); public void init() { /* LAUNCH MESSAGE */ Logger.info(MessageUtil.LAUNCH_MESSAGE); /* LOAD */ this.load(); } private void load() { long mills = System.currentTimeMillis();
ObjectTriple<FileResult, DiscordData, Exception> objectTriple = FileUtil.loadData(Paths.get(CONFIG_LOCATION));
5
2023-10-23 13:24:05+00:00
8k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthPublisherAdapter.java
[ { "identifier": "BaseEthAdapter", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/BaseEthAdapter.java", "snippet": "public abstract class BaseEthAdapter {\n\n private static final BigInteger GAS_LIMIT = BigInteger.valueOf(6721975L);\n private static final BigInteger GAS_PRICE = BigInteger.valueOf(20000000000L);\n\n private final ContractGasProvider contractGasProvider = new ContractGasProvider() {\n @Override\n public BigInteger getGasPrice(String contractFunc) {\n return GAS_PRICE;\n }\n\n @Override\n public BigInteger getGasPrice() {\n return GAS_PRICE;\n }\n\n @Override\n public BigInteger getGasLimit(String contractFunc) {\n return GAS_LIMIT;\n }\n\n @Override\n public BigInteger getGasLimit() {\n return GAS_LIMIT;\n }\n };\n\n private final Web3j web3j;\n\n protected BaseEthAdapter(Web3j web3j) {\n this.web3j = web3j;\n }\n\n protected static Credentials createDummyCredentials() {\n try {\n return Credentials.create(Keys.createEcKeyPair());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public String getCurrentBlockNumber() {\n try {\n BigInteger blockNumber = web3j.ethBlockNumber().sendAsync().get().getBlockNumber();\n return Numeric.toHexStringWithPrefix(blockNumber);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n protected static EthFilter createEventFilter(String contractAddress, String blockNumber,\n Event event) {\n BigInteger blockNum;\n if (blockNumber != null) {\n blockNum = Numeric.toBigInt(blockNumber).add(BigInteger.ONE);\n } else {\n blockNum = BigInteger.ZERO;\n }\n\n DefaultBlockParameter from = DefaultBlockParameter.valueOf(blockNum);\n DefaultBlockParameter to = DefaultBlockParameterName.LATEST;\n\n EthFilter filter = new EthFilter(from, to, contractAddress);\n filter.addSingleTopic(EventEncoder.encode(event));\n return filter;\n }\n\n protected static String getBlockNumberFromEventResponse(BaseEventResponse response) {\n return Numeric.toHexStringWithPrefix(response.log.getBlockNumber());\n }\n\n protected FeedPublisher createPublisherContract(String contractAddr, Credentials credentials) {\n return new FeedPublisherWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected FeedRegistry createRegistryContract(String contractAddr, Credentials credentials) {\n return new FeedRegistryWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected FeedSubscriber createSubscriberContract(String contractAddr, Credentials credentials) {\n return new FeedSubscriberWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected static boolean isValidAddress(String address) {\n return address != null && !address.equals(\"0x0000000000000000000000000000000000000000\");\n }\n\n}" }, { "identifier": "EthUtil", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/EthUtil.java", "snippet": "public final class EthUtil {\n\n private EthUtil() {}\n\n public static String shortenAddress(String addr) {\n return addr.substring(0, 6) + \"...\" + addr.substring(addr.length() - 2);\n }\n\n}" }, { "identifier": "FeedPublisher", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "@SuppressWarnings(\"rawtypes\")\npublic class FeedPublisher extends Contract {\n public static final String BINARY = \"608060405234801561001057600080fd5b50600080546001600160a01b03191633179055604080516060810190915260288082526100459190610b80602083013961004a565b610104565b6100918160405160240161005e91906100b6565b60408051601f198184030181529190526020810180516001600160e01b0390811663104c13eb60e21b1790915261009416565b50565b80516a636f6e736f6c652e6c6f6790602083016000808383865afa5050505050565b600060208083528351808285015260005b818110156100e3578581018301518582016040015282016100c7565b506000604082860101526040601f19601f8301168501019250505092915050565b610a6d806101136000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c80637b7636a11161005b5780637b7636a1146100c05780637c83510f146100e057806384b439c0146100f55780638da5cb5b1461010857600080fd5b806313af4035146100825780631c4bdaa314610097578063243e280b146100ad575b600080fd5b61009561009036600461064b565b610123565b005b6002546040519081526020015b60405180910390f35b6100956100bb366004610691565b610178565b6100d36100ce366004610742565b6102aa565b6040516100a491906107a1565b6100e86103f8565b6040516100a491906107d8565b610095610103366004610691565b61048a565b6000546040516001600160a01b0390911681526020016100a4565b6000546001600160a01b031633146101565760405162461bcd60e51b815260040161014d906107eb565b60405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146101a25760405162461bcd60e51b815260040161014d906107eb565b600280546040805160608101825282815242602082019081529181018581526001840185556000949094528051600384027f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace810191825592517f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5acf84015593519293909290917f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ad0019061025490826108bb565b50505061027b604051806060016040528060228152602001610a166022913933838561058e565b60405181907f6dda240fc875f1ee65b95abd125377f81bf199395a55b7f2ef46c713cae8c29890600090a25050565b6102ce60405180606001604052806000815260200160008152602001606081525090565b600254821061031f5760405162461bcd60e51b815260206004820152601860248201527f507562206974656d20646f6573206e6f74206578697374210000000000000000604482015260640161014d565b600282815481106103325761033261097b565b9060005260206000209060030201604051806060016040529081600082015481526020016001820154815260200160028201805461036f90610833565b80601f016020809104026020016040519081016040528092919081815260200182805461039b90610833565b80156103e85780601f106103bd576101008083540402835291602001916103e8565b820191906000526020600020905b8154815290600101906020018083116103cb57829003601f168201915b5050505050815250509050919050565b60606001805461040790610833565b80601f016020809104026020016040519081016040528092919081815260200182805461043390610833565b80156104805780601f1061045557610100808354040283529160200191610480565b820191906000526020600020905b81548152906001019060200180831161046357829003601f168201915b5050505050905090565b6000546001600160a01b031633146104b45760405162461bcd60e51b815260040161014d906107eb565b60016104c082826108bb565b5061058b6040518060400160405280601d81526020017f4163636f756e742025732073657420666565642055524c3a2027257327000000815250336001805461050890610833565b80601f016020809104026020016040519081016040528092919081815260200182805461053490610833565b80156105815780601f1061055657610100808354040283529160200191610581565b820191906000526020600020905b81548152906001019060200180831161056457829003601f168201915b50505050506105dd565b50565b6105d7848484846040516024016105a89493929190610991565b60408051601f198184030181529190526020810180516001600160e01b0316632d23bb1960e11b179052610629565b50505050565b6106248383836040516024016105f5939291906109d7565b60408051601f198184030181529190526020810180516001600160e01b031663e0e9ad4f60e01b179052610629565b505050565b80516a636f6e736f6c652e6c6f6790602083016000808383865afa5050505050565b60006020828403121561065d57600080fd5b81356001600160a01b038116811461067457600080fd5b9392505050565b634e487b7160e01b600052604160045260246000fd5b6000602082840312156106a357600080fd5b813567ffffffffffffffff808211156106bb57600080fd5b818401915084601f8301126106cf57600080fd5b8135818111156106e1576106e161067b565b604051601f8201601f19908116603f011681019083821181831017156107095761070961067b565b8160405282815287602084870101111561072257600080fd5b826020860160208301376000928101602001929092525095945050505050565b60006020828403121561075457600080fd5b5035919050565b6000815180845260005b8181101561078157602081850181015186830182015201610765565b506000602082860101526020601f19601f83011685010191505092915050565b602081528151602082015260208201516040820152600060408301516060808401526107d0608084018261075b565b949350505050565b602081526000610674602083018461075b565b60208082526028908201527f43616c6c6572206f66207468652066756e6374696f6e206973206e6f7420746860408201526765206f776e65722160c01b606082015260800190565b600181811c9082168061084757607f821691505b60208210810361086757634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111561062457600081815260208120601f850160051c810160208610156108945750805b601f850160051c820191505b818110156108b3578281556001016108a0565b505050505050565b815167ffffffffffffffff8111156108d5576108d561067b565b6108e9816108e38454610833565b8461086d565b602080601f83116001811461091e57600084156109065750858301515b600019600386901b1c1916600185901b1785556108b3565b600085815260208120601f198616915b8281101561094d5788860151825594840194600190910190840161092e565b508582101561096b5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b600052603260045260246000fd5b6080815260006109a4608083018761075b565b6001600160a01b03861660208401526040830185905282810360608401526109cc818561075b565b979650505050505050565b6060815260006109ea606083018661075b565b6001600160a01b03851660208401528281036040840152610a0b818561075b565b969550505050505056fe4163636f756e74202573207075626c6973686564206974656d2025643a2027257327a264697066735822122015025348b2070e170e07b005bee318202c0997e07c9b4a7af027615656f8950964736f6c634300081300335075626c697368657220636f6e747261637420686173206265656e20636f6e737472756374656421\";\n\n public static final String FUNC_GETFEEDURL = \"getFeedUrl\";\n\n public static final String FUNC_GETPUBITEM = \"getPubItem\";\n\n public static final String FUNC_GETTOTALPUBITEMCOUNT = \"getTotalPubItemCount\";\n\n public static final String FUNC_OWNER = \"owner\";\n\n public static final String FUNC_PUBLISH = \"publish\";\n\n public static final String FUNC_SETFEEDURL = \"setFeedUrl\";\n\n public static final String FUNC_SETOWNER = \"setOwner\";\n\n public static final Event NEWPUBITEM_EVENT = new Event(\"NewPubItem\",\n Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>(true) {}));\n\n @Deprecated\n protected FeedPublisher(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n protected FeedPublisher(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, credentials, contractGasProvider);\n }\n\n @Deprecated\n protected FeedPublisher(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n protected FeedPublisher(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public List<NewPubItemEventResponse> getNewPubItemEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(NEWPUBITEM_EVENT, transactionReceipt);\n ArrayList<NewPubItemEventResponse> responses = new ArrayList<NewPubItemEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n NewPubItemEventResponse typedResponse = new NewPubItemEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.num = (BigInteger) eventValues.getIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<NewPubItemEventResponse> newPubItemEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, NewPubItemEventResponse>() {\n @Override\n public NewPubItemEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(NEWPUBITEM_EVENT, log);\n NewPubItemEventResponse typedResponse = new NewPubItemEventResponse();\n typedResponse.log = log;\n typedResponse.num = (BigInteger) eventValues.getIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<NewPubItemEventResponse> newPubItemEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(NEWPUBITEM_EVENT));\n return newPubItemEventFlowable(filter);\n }\n\n public RemoteFunctionCall<String> getFeedUrl() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETFEEDURL,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));\n return executeRemoteCallSingleValueReturn(function, String.class);\n }\n\n public RemoteFunctionCall<PubItem> getPubItem(BigInteger num) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETPUBITEM, \n Arrays.<Type>asList(new Uint256(num)),\n Arrays.<TypeReference<?>>asList(new TypeReference<PubItem>() {}));\n return executeRemoteCallSingleValueReturn(function, PubItem.class);\n }\n\n public RemoteFunctionCall<BigInteger> getTotalPubItemCount() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETTOTALPUBITEMCOUNT,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));\n return executeRemoteCallSingleValueReturn(function, BigInteger.class);\n }\n\n public RemoteFunctionCall<String> owner() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_OWNER,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));\n return executeRemoteCallSingleValueReturn(function, String.class);\n }\n\n public RemoteFunctionCall<TransactionReceipt> publish(String data) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_PUBLISH,\n Arrays.<Type>asList(new Utf8String(data)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> setFeedUrl(String feedUrl) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SETFEEDURL, \n Arrays.<Type>asList(new Utf8String(feedUrl)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> setOwner(String _newOwner) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SETOWNER,\n Arrays.<Type>asList(new Address(160, _newOwner)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n @Deprecated\n public static FeedPublisher load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedPublisher(contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n @Deprecated\n public static FeedPublisher load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedPublisher(contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n public static FeedPublisher load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n return new FeedPublisher(contractAddress, web3j, credentials, contractGasProvider);\n }\n\n public static FeedPublisher load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n return new FeedPublisher(contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n return deployRemoteCall(FeedPublisher.class, web3j, credentials, contractGasProvider, BINARY, \"\");\n }\n\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n return deployRemoteCall(FeedPublisher.class, web3j, transactionManager, contractGasProvider, BINARY, \"\");\n }\n\n @Deprecated\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n return deployRemoteCall(FeedPublisher.class, web3j, credentials, gasPrice, gasLimit, BINARY, \"\");\n }\n\n @Deprecated\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n return deployRemoteCall(FeedPublisher.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, \"\");\n }\n\n public static class PubItem extends DynamicStruct {\n public BigInteger num;\n\n public BigInteger timestamp;\n\n public String data;\n\n public PubItem(BigInteger num, BigInteger timestamp, String data) {\n super(new Uint256(num), new Uint256(timestamp), new Utf8String(data));\n this.num = num;\n this.timestamp = timestamp;\n this.data = data;\n }\n\n public PubItem(Uint256 num, Uint256 timestamp, Utf8String data) {\n super(num, timestamp, data);\n this.num = num.getValue();\n this.timestamp = timestamp.getValue();\n this.data = data.getValue();\n }\n }\n\n public static class NewPubItemEventResponse extends BaseEventResponse {\n public BigInteger num;\n }\n}" }, { "identifier": "NewPubItemEventResponse", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "public static class NewPubItemEventResponse extends BaseEventResponse {\n public BigInteger num;\n}" }, { "identifier": "PubItem", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "public static class PubItem extends DynamicStruct {\n public BigInteger num;\n\n public BigInteger timestamp;\n\n public String data;\n\n public PubItem(BigInteger num, BigInteger timestamp, String data) {\n super(new Uint256(num), new Uint256(timestamp), new Utf8String(data));\n this.num = num;\n this.timestamp = timestamp;\n this.data = data;\n }\n\n public PubItem(Uint256 num, Uint256 timestamp, Utf8String data) {\n super(num, timestamp, data);\n this.num = num.getValue();\n this.timestamp = timestamp.getValue();\n this.data = data.getValue();\n }\n}" } ]
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.NewPubItemEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.PubItem; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter;
5,824
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthPublisherAdapter extends BaseEthAdapter { public interface EventListener {
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthPublisherAdapter extends BaseEthAdapter { public interface EventListener {
void onNewPubItem(String pubContractAddr, String blockNumber, PubItem pubItem);
4
2023-10-23 20:33:07+00:00
8k
UnityFoundation-io/Libre311
app/src/test/java/app/JurisdictionSupportRootControllerTest.java
[ { "identifier": "ServiceDTO", "path": "app/src/main/java/app/dto/service/ServiceDTO.java", "snippet": "@Introspected\npublic class ServiceDTO {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n @JsonProperty(\"service_name\")\n private String serviceName;\n\n private String description;\n\n private boolean metadata;\n\n private ServiceType type;\n\n public ServiceDTO() {\n }\n\n public ServiceDTO(Service service) {\n this.serviceCode = service.getServiceCode();\n this.serviceName = service.getServiceName();\n this.description = service.getDescription();\n this.metadata = service.isMetadata();\n this.type = service.getType();\n if (service.getJurisdiction() != null) {\n this.jurisdictionId = service.getJurisdiction().getId();\n }\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public boolean isMetadata() {\n return metadata;\n }\n\n public void setMetadata(boolean metadata) {\n this.metadata = metadata;\n }\n\n public ServiceType getType() {\n return type;\n }\n\n public void setType(ServiceType type) {\n this.type = type;\n }\n}" }, { "identifier": "PostRequestServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/PostRequestServiceRequestDTO.java", "snippet": "@Introspected\npublic class PostRequestServiceRequestDTO {\n\n @NotBlank\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n @JsonProperty(\"lat\")\n private String latitude;\n\n @JsonProperty(\"long\")\n private String longitude;\n\n @JsonProperty(\"address_string\")\n private String addressString;\n\n // The internal address ID used by a jurisdiction’s master address repository or other addressing system.\n @JsonProperty(\"address_id\")\n private String addressId;\n\n @Email(regexp = \"^[a-zA-Z0-9_+&*-]+(?:\\\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,7}$\")\n private String email;\n\n // The unique device ID of the device submitting the request. This is usually only used for mobile devices.\n @JsonProperty(\"device_id\")\n private String deviceId;\n\n // The unique ID for the user account of the person submitting the request\n @JsonProperty(\"account_id\")\n private String accountId;\n\n @JsonProperty(\"first_name\")\n @Pattern(regexp = \"^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð\\\\-'. ]+$\")\n private String firstName;\n\n @JsonProperty(\"last_name\")\n @Pattern(regexp = \"^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð\\\\-'. ]+$\")\n private String lastName;\n\n private String phone;\n\n @Size(max = 4000)\n private String description;\n\n @JsonProperty(\"media_url\")\n private String mediaUrl;\n\n @NotBlank\n @JsonProperty(\"g_recaptcha_response\")\n private String gRecaptchaResponse;\n\n public PostRequestServiceRequestDTO(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(String latitude) {\n this.latitude = latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(String longitude) {\n this.longitude = longitude;\n }\n\n public String getAddressString() {\n return addressString;\n }\n\n public void setAddressString(String addressString) {\n this.addressString = addressString;\n }\n\n public String getAddressId() {\n return addressId;\n }\n\n public void setAddressId(String addressId) {\n this.addressId = addressId;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(String deviceId) {\n this.deviceId = deviceId;\n }\n\n public String getAccountId() {\n return accountId;\n }\n\n public void setAccountId(String accountId) {\n this.accountId = accountId;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n // see https://github.com/micronaut-projects/micronaut-core/issues/1853\n public Map<String, Object> toMap() {\n Map<String, Object> m = new HashMap<>();\n m.put(\"service_code\", getServiceCode());\n return m;\n }\n\n public String getgRecaptchaResponse() {\n return gRecaptchaResponse;\n }\n\n public void setgRecaptchaResponse(String gRecaptchaResponse) {\n this.gRecaptchaResponse = gRecaptchaResponse;\n }\n\n @Nullable\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(@Nullable String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n}" }, { "identifier": "PostResponseServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/PostResponseServiceRequestDTO.java", "snippet": "public class PostResponseServiceRequestDTO implements ServiceRequestResponseDTO {\n\n @JsonProperty(\"service_request_id\")\n private Long id;\n\n private String token;\n\n // Information about the action expected to fulfill the request or otherwise address the information reported.\n @JsonProperty(\"service_notice\")\n private String serviceNotice;\n\n @JsonProperty(\"account_id\")\n private String accountId;\n\n public PostResponseServiceRequestDTO() {\n }\n\n public PostResponseServiceRequestDTO(ServiceRequest serviceRequest) {\n this.id = serviceRequest.getId();\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getServiceNotice() {\n return serviceNotice;\n }\n\n public void setServiceNotice(String serviceNotice) {\n this.serviceNotice = serviceNotice;\n }\n\n public String getAccountId() {\n return accountId;\n }\n\n public void setAccountId(String accountId) {\n this.accountId = accountId;\n }\n}" }, { "identifier": "ServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/ServiceRequestDTO.java", "snippet": "@Introspected\npublic class ServiceRequestDTO implements ServiceRequestResponseDTO {\n\n @JsonProperty(\"service_request_id\")\n private Long id;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n private ServiceRequestStatus status;\n\n @JsonProperty(\"status_notes\")\n private String statusNotes;\n\n @JsonProperty(\"service_name\")\n private String serviceName;\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n private String description;\n\n @JsonProperty(\"agency_responsible\")\n private String agencyResponsible;\n\n @JsonProperty(\"service_notice\")\n private String serviceNotice;\n\n @JsonProperty(\"requested_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant dateCreated;\n\n @JsonProperty(\"updated_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant dateUpdated;\n\n @JsonProperty(\"expected_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant expectedDate;\n\n @JsonProperty(\"address\")\n private String address;\n\n // The internal address ID used by a jurisdiction’s master address repository or other addressing system.\n @JsonProperty(\"address_id\")\n private String addressId;\n\n @JsonProperty(\"zipcode\")\n private String zipCode;\n\n @JsonProperty(\"lat\")\n private String latitude;\n\n @JsonProperty(\"long\")\n private String longitude;\n\n @JsonProperty(\"media_url\")\n private String mediaUrl;\n\n @JsonProperty(\"selected_values\")\n private List<ServiceDefinitionAttribute> selectedValues;\n\n public ServiceRequestDTO() {\n }\n\n public ServiceRequestDTO(ServiceRequest serviceRequest) {\n this.id = serviceRequest.getId();\n this.status = serviceRequest.getStatus();\n this.statusNotes = serviceRequest.getStatusNotes();\n this.serviceName = serviceRequest.getService().getServiceName();\n this.serviceCode = serviceRequest.getService().getServiceCode();\n this.description = serviceRequest.getDescription();\n this.agencyResponsible = serviceRequest.getAgencyResponsible();\n this.serviceNotice = serviceRequest.getServiceNotice();\n this.dateCreated = serviceRequest.getDateCreated();\n this.dateUpdated = serviceRequest.getDateUpdated();\n this.expectedDate = serviceRequest.getExpectedDate();\n this.address = serviceRequest.getAddressString();\n this.addressId = serviceRequest.getAddressId();\n this.zipCode = serviceRequest.getZipCode();\n this.latitude = serviceRequest.getLatitude();\n this.longitude = serviceRequest.getLongitude();\n this.mediaUrl = serviceRequest.getMediaUrl();\n if (serviceRequest.getJurisdiction() != null) {\n this.jurisdictionId = serviceRequest.getJurisdiction().getId();\n }\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public ServiceRequestStatus getStatus() {\n return status;\n }\n\n public void setStatus(ServiceRequestStatus status) {\n this.status = status;\n }\n\n public String getStatusNotes() {\n return statusNotes;\n }\n\n public void setStatusNotes(String statusNotes) {\n this.statusNotes = statusNotes;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getAgencyResponsible() {\n return agencyResponsible;\n }\n\n public void setAgencyResponsible(String agencyResponsible) {\n this.agencyResponsible = agencyResponsible;\n }\n\n public String getServiceNotice() {\n return serviceNotice;\n }\n\n public void setServiceNotice(String serviceNotice) {\n this.serviceNotice = serviceNotice;\n }\n\n public Instant getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Instant dateCreated) {\n this.dateCreated = dateCreated;\n }\n\n public Instant getDateUpdated() {\n return dateUpdated;\n }\n\n public void setDateUpdated(Instant dateUpdated) {\n this.dateUpdated = dateUpdated;\n }\n\n public Instant getExpectedDate() {\n return expectedDate;\n }\n\n public void setExpectedDate(Instant expectedDate) {\n this.expectedDate = expectedDate;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getAddressId() {\n return addressId;\n }\n\n public void setAddressId(String addressId) {\n this.addressId = addressId;\n }\n\n public String getZipCode() {\n return zipCode;\n }\n\n public void setZipCode(String zipCode) {\n this.zipCode = zipCode;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(String latitude) {\n this.latitude = latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(String longitude) {\n this.longitude = longitude;\n }\n\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n // see https://github.com/micronaut-projects/micronaut-core/issues/1853\n public Map<String, Object> toMap() {\n Map<String, Object> m = new HashMap<>();\n m.put(\"service_code\", getServiceCode());\n return m;\n }\n\n public List<ServiceDefinitionAttribute> getSelectedValues() {\n return selectedValues;\n }\n\n public void setSelectedValues(List<ServiceDefinitionAttribute> selectedValues) {\n this.selectedValues = selectedValues;\n }\n}" }, { "identifier": "ServiceRepository", "path": "app/src/main/java/app/model/service/ServiceRepository.java", "snippet": "@Repository\npublic interface ServiceRepository extends PageableRepository<Service, Long> {\n Optional<Service> findByServiceCode(String serviceCode);\n\n Page<Service> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n\n Optional<Service> findByServiceCodeAndJurisdictionId(String serviceCode, String jurisdictionId);\n}" }, { "identifier": "ServiceRequestRepository", "path": "app/src/main/java/app/model/servicerequest/ServiceRequestRepository.java", "snippet": "@Repository\npublic interface ServiceRequestRepository extends PageableRepository<ServiceRequest, Long> {\n Page<ServiceRequest> findByIdIn(List<Long> serviceRequestIds, Pageable pageable);\n\n Page<ServiceRequest> findByServiceServiceCode(String serviceCode, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCode(String serviceCode);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end);\n\n Page<ServiceRequest> findByStatus(ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByStatus(ServiceRequestStatus status);\n Page<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByDateCreatedBetween(Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBetween(Instant startDate, Instant endDate);\n Page<ServiceRequest> findByDateCreatedAfter(Instant start, Pageable pageable);\n List<ServiceRequest> findByDateCreatedAfter(Instant start);\n Page<ServiceRequest> findByDateCreatedBefore(Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBefore(Instant end);\n\n Optional<ServiceRequest> findByServiceServiceNameIlike(String serviceName);\n\n // jurisdiction\n Optional<ServiceRequest> findByIdAndJurisdictionId(Long serviceRequestId, String jurisdictionId);\n Page<ServiceRequest> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n List<ServiceRequest> findAllByJurisdictionId(String jurisdictionId);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant startDate, Instant endDate);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end);\n}" }, { "identifier": "DbCleanup", "path": "app/src/test/java/app/util/DbCleanup.java", "snippet": "@Singleton\npublic class DbCleanup {\n\n private final ServiceRequestRepository serviceRequestRepository;\n private final JurisdictionRepository jurisdictionRepository;\n\n public DbCleanup(ServiceRequestRepository serviceRequestRepository, JurisdictionRepository jurisdictionRepository) {\n this.serviceRequestRepository = serviceRequestRepository;\n this.jurisdictionRepository = jurisdictionRepository;\n }\n\n @Transactional\n public void cleanupServiceRequests() {\n serviceRequestRepository.deleteAll();\n }\n\n @Transactional\n public void cleanupJurisdictions() {\n jurisdictionRepository.deleteAll();\n }\n}" }, { "identifier": "MockAuthenticationFetcher", "path": "app/src/test/java/app/util/MockAuthenticationFetcher.java", "snippet": "@Replaces(AuthenticationFetcher.class)\n@Singleton\npublic class MockAuthenticationFetcher implements AuthenticationFetcher {\n\n\n private Authentication authentication;\n\n @Override\n public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {\n return Publishers.just(this.authentication);\n }\n\n public void setAuthentication(Authentication authentication) {\n this.authentication = authentication;\n }\n}" }, { "identifier": "MockReCaptchaService", "path": "app/src/test/java/app/util/MockReCaptchaService.java", "snippet": "@Singleton\n@Replaces(ReCaptchaService.class)\npublic class MockReCaptchaService extends ReCaptchaService {\n\n public MockReCaptchaService() {}\n\n public Boolean verifyReCaptcha(String response) {\n return true;\n }\n}" }, { "identifier": "MockSecurityService", "path": "app/src/test/java/app/util/MockSecurityService.java", "snippet": "@Replaces(SecurityService.class)\n@Singleton\npublic class MockSecurityService implements SecurityService {\n\n private ServerAuthentication serverAuthentication;\n\n @PostConstruct\n public void postConstruct() {\n serverAuthentication = new ServerAuthentication(\"[email protected]\",\n null,\n null);\n }\n\n @Override\n public Optional<String> username() {\n return Optional.empty();\n }\n\n @Override\n public Optional<Authentication> getAuthentication() {\n return Optional.of(serverAuthentication);\n }\n\n @Override\n public boolean isAuthenticated() {\n return false;\n }\n\n @Override\n public boolean hasRole(String role) {\n return false;\n }\n\n public void setServerAuthentication(ServerAuthentication serverAuthentication) {\n this.serverAuthentication = serverAuthentication;\n }\n}" } ]
import app.dto.service.ServiceDTO; import app.dto.servicerequest.PostRequestServiceRequestDTO; import app.dto.servicerequest.PostResponseServiceRequestDTO; import app.dto.servicerequest.ServiceRequestDTO; import app.model.service.ServiceRepository; import app.model.servicerequest.ServiceRequestRepository; import app.util.DbCleanup; import app.util.MockAuthenticationFetcher; import app.util.MockReCaptchaService; import app.util.MockSecurityService; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVReader; import com.opencsv.exceptions.CsvValidationException; import io.micronaut.core.util.StringUtils; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.MediaType; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.exceptions.HttpClientResponseException; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import java.util.Optional; import static io.micronaut.http.HttpStatus.INTERNAL_SERVER_ERROR; import static io.micronaut.http.HttpStatus.UNAUTHORIZED; import static org.junit.jupiter.api.Assertions.*;
6,761
// Copyright 2023 Libre311 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 app; @MicronautTest(environments={"test-jurisdiction-support"}) public class JurisdictionSupportRootControllerTest { @Inject @Client("/api") HttpClient client; @Inject MockReCaptchaService mockReCaptchaService; @Inject ServiceRepository serviceRepository; @Inject ServiceRequestRepository serviceRequestRepository; @Inject MockSecurityService mockSecurityService; @Inject MockAuthenticationFetcher mockAuthenticationFetcher; @Inject
// Copyright 2023 Libre311 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 app; @MicronautTest(environments={"test-jurisdiction-support"}) public class JurisdictionSupportRootControllerTest { @Inject @Client("/api") HttpClient client; @Inject MockReCaptchaService mockReCaptchaService; @Inject ServiceRepository serviceRepository; @Inject ServiceRequestRepository serviceRequestRepository; @Inject MockSecurityService mockSecurityService; @Inject MockAuthenticationFetcher mockAuthenticationFetcher; @Inject
DbCleanup dbCleanup;
6
2023-10-18 15:37:36+00:00
8k
JonnyOnlineYT/xenza
src/minecraft/net/augustus/modules/player/Regen.java
[ { "identifier": "EventTick", "path": "src/minecraft/net/augustus/events/EventTick.java", "snippet": "public class EventTick extends Event {\n}" }, { "identifier": "Categorys", "path": "src/minecraft/net/augustus/modules/Categorys.java", "snippet": "public enum Categorys {\n MOVEMENT,\n COMBAT,\n PLAYER,\n MISC,\n RENDER,\n WORLD;\n\n public Color color;\n\n Categorys() {\n color = new Color(RandomUtil.nextInt(0, 255), RandomUtil.nextInt(0, 255), RandomUtil.nextInt(0, 255));\n }\n\n public Color getColor() {\n return color;\n }\n}" }, { "identifier": "Module", "path": "src/minecraft/net/augustus/modules/Module.java", "snippet": "public class Module implements MC, MM, SM, Comparable<Module> {\n public Animation yPos = new Animation();\n public Animation xPos = new Animation();\n @Expose\n @SerializedName(\"Name\")\n private String name;\n private String displayName = \"\";\n @Expose\n @SerializedName(\"Toggled\")\n private boolean toggled;\n @Expose\n @SerializedName(\"Key\")\n private int key;\n @Expose\n @SerializedName(\"Category\")\n private Categorys category;\n private Color color;\n private float x;\n private float y;\n private float minX;\n private float maxX;\n private float moduleWidth = 0.0F;\n public AnimationUtil animationUtil;\n protected ScaledResolution sr = new ScaledResolution(mc);\n public SecureRandom RANDOM = new SecureRandom();\n\n public Module(String name, Color color, Categorys category) {\n this.name = name;\n this.color = color;\n this.category = category;\n this.displayName = name;\n Augustus.getInstance().getManager().getModules().add(this);\n }\n\n public final void toggle() {\n if (this.toggled) {\n if (mc.theWorld != null && mm.arrayList.toggleSound.getBoolean() && !this.equals(mm.clickGUI)) {\n SoundUtil.play(SoundUtil.toggleOffSound);\n }\n //NotificationsManager.addNotification(new Notification(\"Toggled \" + name + \" off\", Notification.Type.ToggleOff));\n GeneralNotifyManager.addNotification(\"Toggled \" + name + \" off\", NotificationType.ToggleOff);\n this.toggled = false;\n mm.getActiveModules().remove(this);\n this.onPreDisable();\n EventManager.unregister(this);\n this.onDisable();\n } else {\n if (mc.theWorld != null && mm.arrayList.toggleSound.getBoolean() && !this.equals(mm.clickGUI)) {\n SoundUtil.play(SoundUtil.toggleOnSound);\n }\n //NotificationsManager.addNotification(new Notification(\"Toggled \" + name + \" on\", Notification.Type.ToggleOn));\n GeneralNotifyManager.addNotification(\"Toggled \" + name + \" on\", NotificationType.ToggleOn);\n this.toggled = true;\n if (!(this instanceof ClickGUI)) {\n mm.getActiveModules().add(this);\n }\n\n this.onEnable();\n EventManager.register(this);\n }\n\n mm.arrayList.updateSorting();\n }\n\n public void updatePos() {\n if (this.isToggled()) {\n if (this.getXPos().getTarget() != Augustus.getInstance().getLoriousFontService().getComfortaa18().getStringWidth(this.getDisplayName()) + 5.0) {\n this.getXPos().animate(Augustus.getInstance().getLoriousFontService().getComfortaa18().getStringWidth(this.getDisplayName()) + 5.0, 350.0, Easings.QUAD_BOTH);\n }\n } else if (this.getXPos().getTarget() != -5.0) {\n this.getXPos().animate(-5.0, 350.0, Easings.QUAD_BOTH);\n }\n }\n\n public void onEnable() {\n }\n\n public void onDisable() {\n }\n\n public void onPreDisable() {\n }\n\n public Animation getYPos() {\n return this.yPos;\n }\n\n public Animation getXPos() {\n return this.xPos;\n }\n\n public Color getColor() {\n return this.color;\n }\n\n public void setColor(Color color) {\n this.color = color;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDisplayName() {\n return this.displayName;\n }\n\n public void setDisplayName(String displayName) {\n String lastName = this.displayName;\n if (mc.thePlayer != null) {\n if (mm.arrayList.isToggled() && mm.arrayList.suffix.getBoolean()) {\n this.displayName = displayName;\n } else {\n this.displayName = this.name;\n }\n } else {\n this.displayName = displayName;\n }\n\n if (!this.displayName.equalsIgnoreCase(lastName)) {\n mm.arrayList.updateSorting();\n }\n }\n\n public boolean isToggled() {\n return this.toggled;\n }\n\n public void setToggled(boolean toggled) {\n if (this.toggled != toggled) {\n this.toggle();\n }\n }\n\n public int getKey() {\n return this.key;\n }\n\n public void setKey(int key) {\n this.key = key;\n }\n\n public Categorys getCategory() {\n return this.category;\n }\n\n public void setCategory(Categorys category) {\n this.category = category;\n }\n\n public float getX() {\n return this.x;\n }\n\n public void setX(float x) {\n this.x = x;\n }\n\n public float getY() {\n return this.y;\n }\n\n public void setY(float y) {\n this.y = y;\n }\n\n public float getMaxX() {\n return this.maxX;\n }\n\n public void setMaxX(float maxX) {\n this.maxX = maxX;\n }\n\n public float getMinX() {\n return this.minX;\n }\n\n public void setMinX(float minX) {\n this.minX = minX;\n }\n\n public AnimationUtil getAnimationUtil() {\n return this.animationUtil;\n }\n\n public float getModuleWidth() {\n return this.moduleWidth;\n }\n\n public void setModuleWidth(float moduleWidth) {\n this.moduleWidth = moduleWidth;\n }\n\n public void setAnimationUtil(AnimationUtil animationUtil) {\n this.animationUtil = animationUtil;\n }\n\n public void readModule(Module module) {\n this.setName(module.getName());\n if (!(this instanceof ClickGUI)) {\n this.setToggled(module.isToggled());\n }\n\n this.setCategory(module.getCategory());\n this.setKey(module.getKey());\n }\n\n public void readConfig(Module module) {\n if (!(this instanceof ClickGUI)) {\n this.setToggled(module.isToggled());\n }\n }\n\n public int compareTo(Module module) {\n if (mm.arrayList.sortOption.getSelected().equals(\"Alphabet\")) {\n return -module.getName().compareTo(this.getName());\n } else {\n return mm.arrayList.font.getSelected().equals(\"Minecraft\")\n ? mc.fontRendererObj.getStringWidth(module.getDisplayName()) - mc.fontRendererObj.getStringWidth(this.getDisplayName())\n : Math.round(\n mm.arrayList.getCustomFont().getStringWidth(module.getDisplayName())\n - mm.arrayList.getCustomFont().getStringWidth(FontRenderer.getFormatFromString(module.getDisplayName()))\n - (\n mm.arrayList.getCustomFont().getStringWidth(this.getDisplayName())\n - mm.arrayList.getCustomFont().getStringWidth(FontRenderer.getFormatFromString(this.getDisplayName()))\n )\n );\n }\n }\n\n public String getSuffix() {\n return this.displayName.replace(this.name, \"\");\n }\n}" }, { "identifier": "BooleanValue", "path": "src/minecraft/net/augustus/settings/BooleanValue.java", "snippet": "public class BooleanValue extends Setting {\n @Expose\n @SerializedName(\"Boolean\")\n private boolean aBoolean;\n\n public BooleanValue(int id, String name, Module parent, boolean aBoolean) {\n super(id, name, parent);\n this.aBoolean = aBoolean;\n sm.newSetting(this);\n }\n\n public boolean getBoolean() {\n return this.aBoolean;\n }\n\n public void setBoolean(boolean aBoolean) {\n this.aBoolean = aBoolean;\n }\n\n @Override\n public void readSetting(SettingPart setting) {\n super.readSetting(setting);\n this.setBoolean(setting.isaBoolean());\n }\n\n @Override\n public void readConfigSetting(SettingPart setting) {\n super.readConfigSetting(setting);\n this.setBoolean(setting.isaBoolean());\n }\n}" }, { "identifier": "DoubleValue", "path": "src/minecraft/net/augustus/settings/DoubleValue.java", "snippet": "public class DoubleValue extends Setting {\n @Expose\n @SerializedName(\"Value\")\n private double value;\n private double minValue;\n private double maxValue;\n private int decimalPlaces;\n\n public DoubleValue(int id, String name, Module parent, double value, double minValue, double maxValue, int decimalPlaces) {\n super(id, name, parent);\n this.value = value;\n this.minValue = minValue;\n this.maxValue = maxValue;\n this.decimalPlaces = decimalPlaces;\n sm.newSetting(this);\n }\n\n public double getValue() {\n return this.value;\n }\n\n public void setValue(double value) {\n this.value = value;\n }\n\n public double getMinValue() {\n return this.minValue;\n }\n\n public void setMinValue(double minValue) {\n this.minValue = minValue;\n }\n\n public double getMaxValue() {\n return this.maxValue;\n }\n\n public void setMaxValue(double maxValue) {\n this.maxValue = maxValue;\n }\n\n public int getDecimalPlaces() {\n return this.decimalPlaces;\n }\n\n public void setDecimalPlaces(int decimalPlaces) {\n this.decimalPlaces = decimalPlaces;\n }\n\n @Override\n public void readSetting(SettingPart setting) {\n super.readSetting(setting);\n this.setValue(setting.getValue());\n }\n\n @Override\n public void readConfigSetting(SettingPart setting) {\n super.readConfigSetting(setting);\n this.setValue(setting.getValue());\n }\n}" }, { "identifier": "C03PacketPlayer", "path": "src/minecraft/net/minecraft/network/play/client/C03PacketPlayer.java", "snippet": "public class C03PacketPlayer implements Packet<INetHandlerPlayServer> {\n protected double x;\n protected double y;\n protected double z;\n protected float yaw;\n protected float pitch;\n protected boolean onGround;\n protected boolean moving;\n protected boolean rotating;\n\n public C03PacketPlayer() {\n }\n\n public C03PacketPlayer(boolean isOnGround) {\n this.onGround = isOnGround;\n }\n\n public void processPacket(INetHandlerPlayServer handler) {\n handler.processPlayer(this);\n }\n\n @Override\n public void readPacketData(PacketBuffer buf) throws IOException {\n this.onGround = buf.readUnsignedByte() != 0;\n }\n\n @Override\n public void writePacketData(PacketBuffer buf) throws IOException {\n buf.writeByte(this.onGround ? 1 : 0);\n }\n\n public double getPositionX() {\n return this.x;\n }\n\n public double getPositionY() {\n return this.y;\n }\n\n public double getPositionZ() {\n return this.z;\n }\n\n public float getYaw() {\n return this.yaw;\n }\n\n public float getPitch() {\n return this.pitch;\n }\n\n public boolean isOnGround() {\n return this.onGround;\n }\n\n public boolean isMoving() {\n return this.moving;\n }\n\n public boolean getRotating() {\n return this.rotating;\n }\n\n public void setMoving(boolean isMoving) {\n this.moving = isMoving;\n }\n\n public void setOnGround(boolean onGround) {\n this.onGround = onGround;\n }\n\n public void setX(double x) {\n this.x = x;\n }\n\n public void setY(double y) {\n this.y = y;\n }\n\n public void setZ(double z) {\n this.z = z;\n }\n\n public static class C04PacketPlayerPosition extends C03PacketPlayer {\n public C04PacketPlayerPosition() {\n this.moving = true;\n }\n\n public C04PacketPlayerPosition(double posX, double posY, double posZ, boolean isOnGround) {\n this.x = posX;\n this.y = posY;\n this.z = posZ;\n this.onGround = isOnGround;\n this.moving = true;\n }\n\n @Override\n public void readPacketData(PacketBuffer buf) throws IOException {\n this.x = buf.readDouble();\n this.y = buf.readDouble();\n this.z = buf.readDouble();\n super.readPacketData(buf);\n }\n\n @Override\n public void writePacketData(PacketBuffer buf) throws IOException {\n buf.writeDouble(this.x);\n buf.writeDouble(this.y);\n buf.writeDouble(this.z);\n super.writePacketData(buf);\n }\n }\n\n public static class C05PacketPlayerLook extends C03PacketPlayer {\n public C05PacketPlayerLook() {\n this.rotating = true;\n }\n\n public C05PacketPlayerLook(float playerYaw, float playerPitch, boolean isOnGround) {\n this.yaw = playerYaw;\n this.pitch = playerPitch;\n this.onGround = isOnGround;\n this.rotating = true;\n }\n\n @Override\n public void readPacketData(PacketBuffer buf) throws IOException {\n this.yaw = buf.readFloat();\n this.pitch = buf.readFloat();\n super.readPacketData(buf);\n }\n\n @Override\n public void writePacketData(PacketBuffer buf) throws IOException {\n buf.writeFloat(this.yaw);\n buf.writeFloat(this.pitch);\n super.writePacketData(buf);\n }\n }\n\n public static class C06PacketPlayerPosLook extends C03PacketPlayer {\n public C06PacketPlayerPosLook() {\n this.moving = true;\n this.rotating = true;\n }\n\n public C06PacketPlayerPosLook(double playerX, double playerY, double playerZ, float playerYaw, float playerPitch, boolean playerIsOnGround) {\n this.x = playerX;\n this.y = playerY;\n this.z = playerZ;\n this.yaw = playerYaw;\n this.pitch = playerPitch;\n this.onGround = playerIsOnGround;\n this.rotating = true;\n this.moving = true;\n }\n\n @Override\n public void readPacketData(PacketBuffer buf) throws IOException {\n this.x = buf.readDouble();\n this.y = buf.readDouble();\n this.z = buf.readDouble();\n this.yaw = buf.readFloat();\n this.pitch = buf.readFloat();\n super.readPacketData(buf);\n }\n\n @Override\n public void writePacketData(PacketBuffer buf) throws IOException {\n buf.writeDouble(this.x);\n buf.writeDouble(this.y);\n buf.writeDouble(this.z);\n buf.writeFloat(this.yaw);\n buf.writeFloat(this.pitch);\n super.writePacketData(buf);\n }\n\n public void setYaw(float v) {\n this.yaw = v;\n }\n }\n}" } ]
import java.awt.Color; import net.augustus.events.EventTick; import net.augustus.modules.Categorys; import net.augustus.modules.Module; import net.augustus.settings.BooleanValue; import net.augustus.settings.DoubleValue; import net.lenni0451.eventapi.reflection.EventTarget; import net.minecraft.network.play.client.C03PacketPlayer;
4,132
package net.augustus.modules.player; public class Regen extends Module { public final DoubleValue health = new DoubleValue(2, "Health", this, 20.0, 0.0, 20.0, 0); public final DoubleValue hunger = new DoubleValue(1, "MinHunger", this, 5.0, 0.0, 20.0, 0); public final DoubleValue packets = new DoubleValue(3, "Packets", this, 100.0, 0.0, 200.0, 0); public final BooleanValue groundCheck = new BooleanValue(4, "GroundCheck", this, false); public Regen() { super("Regen", new Color(224, 111, 49), Categorys.PLAYER); } @EventTarget public void onEventTick(EventTick eventTick) { if ((double)mc.thePlayer.getFoodStats().getFoodLevel() > this.hunger.getValue() && (double)mc.thePlayer.getHealth() < this.health.getValue()) { for(int i = 0; (double)i < this.packets.getValue(); ++i) { if (this.groundCheck.getBoolean()) {
package net.augustus.modules.player; public class Regen extends Module { public final DoubleValue health = new DoubleValue(2, "Health", this, 20.0, 0.0, 20.0, 0); public final DoubleValue hunger = new DoubleValue(1, "MinHunger", this, 5.0, 0.0, 20.0, 0); public final DoubleValue packets = new DoubleValue(3, "Packets", this, 100.0, 0.0, 200.0, 0); public final BooleanValue groundCheck = new BooleanValue(4, "GroundCheck", this, false); public Regen() { super("Regen", new Color(224, 111, 49), Categorys.PLAYER); } @EventTarget public void onEventTick(EventTick eventTick) { if ((double)mc.thePlayer.getFoodStats().getFoodLevel() > this.hunger.getValue() && (double)mc.thePlayer.getHealth() < this.health.getValue()) { for(int i = 0; (double)i < this.packets.getValue(); ++i) { if (this.groundCheck.getBoolean()) {
mc.thePlayer.sendQueue.addToSendQueueDirect(new C03PacketPlayer(mc.thePlayer.onGround));
5
2023-10-15 00:21:15+00:00
8k
Radekyspec/TasksMaster
src/main/java/data_access/HttpDataAccessObject.java
[ { "identifier": "LoginUserDataAccessInterface", "path": "src/main/java/data_access/login/LoginUserDataAccessInterface.java", "snippet": "public interface LoginUserDataAccessInterface {\n User login(String username, String password);\n}" }, { "identifier": "MessageBoardUserDataAccessInterface", "path": "src/main/java/data_access/message_board/MessageBoardUserDataAccessInterface.java", "snippet": "public interface MessageBoardUserDataAccessInterface {\n List<Message> getMessages(long projectID, long messageBoardID);\n\n List<Comment> getComments(long projectID, long messageID);\n\n Comment addComment(long projectID, long messageID, User user, String newComment);\n\n Message addMessage(long projectID, long messageBoardID, User author, String messageTitle, String messageContent);\n}" }, { "identifier": "ProjectUserDataAccessInterface", "path": "src/main/java/data_access/project/ProjectUserDataAccessInterface.java", "snippet": "public interface ProjectUserDataAccessInterface {\n List<Project> getAllProjects();\n\n boolean addProjectMember(Project project, String username);\n\n String getApiErrorMessage();\n\n boolean exists(String username, Project project);\n}" }, { "identifier": "AddProjectUserDataAccessInterface", "path": "src/main/java/data_access/project/add/AddProjectUserDataAccessInterface.java", "snippet": "public interface AddProjectUserDataAccessInterface {\n Project createProject(User user, String name, String description);\n\n String getApiErrorMessage();\n}" }, { "identifier": "ChooseProjectUserDataAccessInterface", "path": "src/main/java/data_access/project/choose/ChooseProjectUserDataAccessInterface.java", "snippet": "public interface ChooseProjectUserDataAccessInterface {\n List<Project> getUserProjects(User user);\n\n String getApiErrorMessage();\n}" }, { "identifier": "ScheduleDataAccessInterface", "path": "src/main/java/data_access/schedule/ScheduleDataAccessInterface.java", "snippet": "public interface ScheduleDataAccessInterface {\n List<Event> getEvents(long projectId, long scheduleid);\n\n Event addEvents(long projectId, long scheduleId, String eventName, String notes, Date startAt, Date endAt, boolean isAllDay, List<String> userWith);\n}" }, { "identifier": "SignupUserDataAccessInterface", "path": "src/main/java/data_access/signup/SignupUserDataAccessInterface.java", "snippet": "public interface SignupUserDataAccessInterface {\n boolean exists(String username);\n\n void save(User user);\n}" }, { "identifier": "AddToDoUserDataAccessInterface", "path": "src/main/java/data_access/todo/add/AddToDoUserDataAccessInterface.java", "snippet": "public interface AddToDoUserDataAccessInterface {\n /**\n * Create a new to_do List. Add data passed in.\n * Data should come from an Interactor.\n *\n * @param projectID receive toDoID\n * @param listID receive listID\n * @param target receive target\n * @param progress receive progress\n * @return a finished, non-empty ToDoList.\n */\n ToDo createToDo(long projectID, long listID, String target, String progress);\n\n /**\n * namely\n *\n * @return A string which is the Api error Message.\n */\n String getApiErrorMessage();\n}" }, { "identifier": "ToDoListDataAccessInterface", "path": "src/main/java/data_access/todolist/ToDoListDataAccessInterface.java", "snippet": "public interface ToDoListDataAccessInterface {\n /**\n * Get to_dos from api.\n *\n * @param projectID namely.\n * @param toDoListID namely.\n * @return A list of To_Do.\n */\n List<ToDo> importToDo(long projectID, long toDoListID);\n\n /**\n * namely\n *\n * @return A string which is the Api error Message.\n */\n String getApiErrorMessage();\n}" }, { "identifier": "AddToDoListUserDataAccessInterface", "path": "src/main/java/data_access/todolist/add/AddToDoListUserDataAccessInterface.java", "snippet": "public interface AddToDoListUserDataAccessInterface {\n /**\n * Create a new to_do List. Add data passed in.\n * Data should come from an Interactor.\n *\n * @param projectID receive projectID\n * @param toDoPanelID receive listID\n * @param name receive name\n * @param detail receive detail\n * @return a finished, non-empty ToDoList.\n */\n ToDoList createToDoList(long projectID, long toDoPanelID, String name, String detail);\n\n /**\n * namely\n *\n * @return A string which is the Api error Message.\n */\n String getApiErrorMessage();\n}" }, { "identifier": "ToDoPanelDataAccessInterface", "path": "src/main/java/data_access/todopanel/ToDoPanelDataAccessInterface.java", "snippet": "public interface ToDoPanelDataAccessInterface {\n /**\n * Get lists from api.\n *\n * @param projectID namely.\n * @param toDoPanelID namely.\n * @return A list of ToDoList.\n */\n List<ToDoList> importToDoList(long projectID, long toDoPanelID);\n\n /**\n * namely\n *\n * @return A string which is the Api error Message.\n */\n String getApiErrorMessage();\n}" }, { "identifier": "Comment", "path": "src/main/java/entities/comment/Comment.java", "snippet": "public interface Comment {\n /**\n * Return the ID of the comment\n *\n * @return its ID\n */\n long getId();\n\n /**\n * Return the Author of the comment\n *\n * @return its author\n */\n String getAuthor();\n\n /**\n * Return the content of the comment\n *\n * @return its content\n */\n String getContent();\n}" }, { "identifier": "CommonCommentFactory", "path": "src/main/java/entities/comment/CommonCommentFactory.java", "snippet": "public class CommonCommentFactory {\n /**\n * create up the new comment with user\n *\n * @param ID the ID of the comment\n * @param author the author of the comment\n * @param content the content of the comment\n */\n public static CommonComment create(long ID, String author, String content) {\n return new CommonComment(ID, author, content);\n }\n}" }, { "identifier": "CommonEventFactory", "path": "src/main/java/entities/event/CommonEventFactory.java", "snippet": "public class CommonEventFactory {\n /**\n * build up an event object.\n *\n * @param id the id of event\n * @param name the name of event\n * @param notes the notes of event\n * @param startsAt starting time of event\n * @param endsAt ending time of event\n * @param isAllDay whether the event is all day\n */\n public static CommonEvent create(long id, String name, String notes, Date startsAt, Date endsAt,\n boolean isAllDay) {\n return new CommonEvent(id, name, notes, startsAt, endsAt, isAllDay);\n }\n}" }, { "identifier": "Event", "path": "src/main/java/entities/event/Event.java", "snippet": "public interface Event {\n /**\n * Return the ID of the Event\n *\n * @return its ID\n */\n long getID();\n\n /**\n * Return the name of the Event\n *\n * @return its name\n */\n String getName();\n\n /**\n * Return the Notes of the Event\n *\n * @return its Notes\n */\n String getNotes();\n\n /**\n * Return the start time of the Event\n *\n * @return its start time\n */\n Date getStartsAt();\n\n /**\n * Return the end time of the Event\n *\n * @return its end time\n */\n Date getEndAt();\n\n /**\n * Return whether the event is All-day\n *\n * @return whether the event is All-day\n */\n boolean getIsAllDay();\n\n /**\n * Return who will join the event\n *\n * @return who will join the event\n */\n List<User> getUserLists();\n\n /**\n * join the Event\n */\n void joinEvent(User user);\n}" }, { "identifier": "CommonMessageFactory", "path": "src/main/java/entities/message/CommonMessageFactory.java", "snippet": "public class CommonMessageFactory {\n /**\n * build up the CommonMessage object\n *\n * @param ID the ID of message\n * @param author the author of message\n * @param title the tittle of message\n * @param content the content of message\n */\n public static CommonMessage create(long ID, String author, String title, String content) {\n return new CommonMessage(ID, author, title, content);\n }\n}" }, { "identifier": "Message", "path": "src/main/java/entities/message/Message.java", "snippet": "public interface Message {\n /**\n * Return the ID of the Message\n *\n * @return its ID\n */\n long getID();\n\n /**\n * Return the Author of the message\n *\n * @return its Author\n */\n String getAuthor();\n\n /**\n * Return the Tittle of the message\n *\n * @return its tittle\n */\n String getTitle();\n\n /**\n * Return the content of the message\n *\n * @return its content\n */\n String getContent();\n\n /**\n * Return the comments of the message\n *\n * @return its comments\n */\n Map<Long, Comment> getComments();\n\n /**\n * add new comment to the message\n *\n * @param comment a comments object.\n */\n void addComment(Comment comment);\n}" }, { "identifier": "CommonMessageBoardFactory", "path": "src/main/java/entities/message_board/CommonMessageBoardFactory.java", "snippet": "public class CommonMessageBoardFactory {\n /**\n * create a new MessageBoard which containing many massage\n *\n * @param ID the ID of the messageBoard\n * @return return a new messageBoard that we build\n */\n public static CommonMessageBoard create(long ID) {\n return new CommonMessageBoard(ID);\n }\n}" }, { "identifier": "CommonProjectFactory", "path": "src/main/java/entities/project/CommonProjectFactory.java", "snippet": "public class CommonProjectFactory {\n /**\n * Create a CommonProject object.\n *\n * @param ID the ID of the project\n * @param name the name of the project\n * @param description the description of the project\n */\n public static CommonProject create(long ID, String name, String description) {\n return new CommonProject(ID, name, description);\n }\n}" }, { "identifier": "Project", "path": "src/main/java/entities/project/Project.java", "snippet": "public interface Project {\n /**\n * Return the ID of the Project\n *\n * @return its ID\n */\n long getID();\n\n String getLeader();\n\n void setLeader(String leader);\n\n /**\n * Return the name of the Project\n *\n * @return its name\n */\n String getName();\n\n String getDescription();\n\n /**\n * Return all members of the Project\n *\n * @return its members\n */\n List<String> getMembers();\n\n /**\n * Return the to_do panel of the Project\n *\n * @return a to_do panel of the current project\n */\n ToDoPanel getToDoPanel();\n\n /**\n * Set the to_do panel as current to_do panel for the project\n *\n * @param toDoPanel a to_do panel object\n */\n void setToDoPanel(ToDoPanel toDoPanel);\n\n /**\n * Return the MessageBoard of the Project\n *\n * @return a message_board of the current project\n */\n MessageBoard getMessageBoard();\n\n /**\n * Set the message_board as current message_board for the project\n *\n * @param messageBoard a message_board object\n */\n void setMessageBoard(MessageBoard messageBoard);\n\n /**\n * Return the schedule of the Project\n *\n * @return a schedule of the current project\n */\n Schedule getSchedule();\n\n /**\n * Set the schedule as current schedule for the project\n *\n * @param schedule a schedule object\n */\n void setSchedule(Schedule schedule);\n\n /**\n * add new member into the project\n *\n * @param newMember the new member that join the project\n */\n void addNewMember(String newMember);\n}" }, { "identifier": "CommonScheduleFactory", "path": "src/main/java/entities/schedule/CommonScheduleFactory.java", "snippet": "public class CommonScheduleFactory {\n /**\n * build up a new schedule\n *\n * @param id the id of the schedule\n */\n public static CommonSchedule create(long id) {\n return new CommonSchedule(id);\n }\n}" }, { "identifier": "CommonToDoFactory", "path": "src/main/java/entities/todo/CommonToDoFactory.java", "snippet": "public class CommonToDoFactory {\n /**\n * create a CommonToDo class that contains basic information about a To_Do.\n *\n * @param ID the identification of this To_Do\n * @param target the aim, or say goal, of this To_Do\n * @param assignedTo people who are assigned to with this to_do.\n * @return a CommonToDo class.\n */\n public static CommonToDo create(long ID, String target, String[] assignedTo, String progress) {\n return new CommonToDo(ID, target, assignedTo, progress);\n }\n\n}" }, { "identifier": "ToDo", "path": "src/main/java/entities/todo/ToDo.java", "snippet": "public interface ToDo {\n final String TODO_INCOMPLETE = \"incomplete\";\n final String TODO_COMPLETE = \"complete\";\n\n /**\n * Returns target of this obj.\n *\n * @return its target.\n */\n long getID();\n\n /**\n * Returns ID of this obj.\n *\n * @return its ID.\n */\n String getTarget();\n\n /**\n * Returns the people who assignTo this obj.\n *\n * @return its assignTo[].\n */\n String[] getAssignedTo();\n\n /**\n * Return if the to_do is finished.\n *\n * @return \"incomplete\" when it isn't complete, done when it's \"complete\".\n */\n String getProgress();\n\n /**\n * Return [ ] if it's unfinished, and return [x] if it's finished.\n *\n * @return a string that graphically shows finish or not.\n */\n String getCharProgress();\n}" }, { "identifier": "CommonToDoListFactory", "path": "src/main/java/entities/todo_list/CommonToDoListFactory.java", "snippet": "public class CommonToDoListFactory {\n /**\n * create a CommonToDoList class that contains things as followed.\n *\n * @param listID the identification of this To_DoList\n * @param name the name of this list\n * @param detail a brief description word that talks about this To_DoList.\n * @return a CommonToDoList\n */\n public static CommonToDoList create(long listID, long projectID, String name, String detail) {\n return new CommonToDoList(listID, projectID, name, detail);\n }\n}" }, { "identifier": "ToDoList", "path": "src/main/java/entities/todo_list/ToDoList.java", "snippet": "public interface ToDoList {\n /**\n * Returns ID of this obj.\n *\n * @return its ID.\n */\n long getListID();\n\n /**\n * Returns name of this obj.\n *\n * @return its name.\n */\n String getName();\n\n /**\n * Returns detail of this obj.\n * A brief description of this TO_DoList\n *\n * @return its detail.\n */\n String getDetail();\n\n /**\n * Returns toDos of this obj.\n * A Map contains pairs of (ID of TO_DO, TO_DO)\n *\n * @return A map contains pairs of id and to_do.\n */\n Map<Long, ToDo> getToDos();\n\n /**\n * add a new to_do into the to_do list\n */\n void addToDos(ToDo toDo);\n\n long getProjectID();\n}" }, { "identifier": "CommonToDoPanelFactory", "path": "src/main/java/entities/todo_panel/CommonToDoPanelFactory.java", "snippet": "public class CommonToDoPanelFactory {\n /**\n * create a CommonToDoPanel class that contains things as followed.\n *\n * @param ID the identification of this To_DoPanel\n * @return a CommonToDoPanel class\n */\n public static CommonToDoPanel create(long ID) {\n return new CommonToDoPanel(ID);\n }\n}" }, { "identifier": "User", "path": "src/main/java/entities/user/User.java", "snippet": "public interface User {\n /**\n * Return the ID of the User\n *\n * @return its ID\n */\n long getID();\n\n /**\n * Return the organization that User is in\n *\n * @return its organization\n */\n Organization getOrganization();\n\n /**\n * Return the name of the User\n *\n * @return its name\n */\n String getName();\n\n /**\n * Return the password of the User\n *\n * @return its password\n */\n String getPassword();\n\n /**\n * Return the created time of the User\n *\n * @return its creation_time\n */\n LocalDateTime getCreationTime();\n\n /**\n * Return the email of the User\n *\n * @return its email\n */\n String getEmail();\n\n Rule getRule();\n\n /**\n * set and get the rule of the User, including Boss, Leader and Member\n */\n\n void setRule(Rule rule);\n\n /**\n * let user join a organization\n *\n * @param organization an organization that user want to join\n */\n void joinOrganization(Organization organization);\n\n}" }, { "identifier": "InvalidApiKeyException", "path": "src/main/java/exceptions/InvalidApiKeyException.java", "snippet": "public class InvalidApiKeyException extends Exception {\n public InvalidApiKeyException(String apiKeyErrorMessage) {\n super(apiKeyErrorMessage);\n }\n}" } ]
import data_access.login.LoginUserDataAccessInterface; import data_access.message_board.MessageBoardUserDataAccessInterface; import data_access.project.ProjectUserDataAccessInterface; import data_access.project.add.AddProjectUserDataAccessInterface; import data_access.project.choose.ChooseProjectUserDataAccessInterface; import data_access.schedule.ScheduleDataAccessInterface; import data_access.signup.SignupUserDataAccessInterface; import data_access.todo.add.AddToDoUserDataAccessInterface; import data_access.todolist.ToDoListDataAccessInterface; import data_access.todolist.add.AddToDoListUserDataAccessInterface; import data_access.todopanel.ToDoPanelDataAccessInterface; import entities.comment.Comment; import entities.comment.CommonCommentFactory; import entities.event.CommonEventFactory; import entities.event.Event; import entities.message.CommonMessageFactory; import entities.message.Message; import entities.message_board.CommonMessageBoardFactory; import entities.project.CommonProjectFactory; import entities.project.Project; import entities.schedule.CommonScheduleFactory; import entities.todo.CommonToDoFactory; import entities.todo.ToDo; import entities.todo_list.CommonToDoListFactory; import entities.todo_list.ToDoList; import entities.todo_panel.CommonToDoPanelFactory; import entities.user.User; import exceptions.InvalidApiKeyException; import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.stream.Collectors;
5,141
package data_access; public abstract class HttpDataAccessObject implements SignupUserDataAccessInterface, LoginUserDataAccessInterface, ProjectUserDataAccessInterface, ChooseProjectUserDataAccessInterface, AddProjectUserDataAccessInterface, MessageBoardUserDataAccessInterface, AddToDoUserDataAccessInterface, ToDoListDataAccessInterface, AddToDoListUserDataAccessInterface, ToDoPanelDataAccessInterface, ScheduleDataAccessInterface { private final String API_KEY; private final OkHttpClient client = new OkHttpClient().newBuilder() .build(); private long orgId; private String error; public HttpDataAccessObject(String apiKey) throws InvalidApiKeyException { API_KEY = apiKey; if (!isValidApiKey()) { throw new InvalidApiKeyException(getApiErrorMessage()); } } private Request.Builder buildRequest() { return new Request.Builder() .addHeader("Authorization", "Bearer " + API_KEY) .addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("User-Agent", "TasksMaster ([email protected])"); } private boolean isValidApiKey() { if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) { return false; } Request request = buildRequest() .url("https://launchpad.37signals.com/authorization.json") .build(); try { Response response = client.newCall(request).execute(); if (response.code() != 200 || response.body() == null) { setErrorMessage("Network Error"); return false; } JSONObject lastResponse = new JSONObject(response.body().string()); if (!lastResponse.has("error")) { orgId = lastResponse.getJSONArray("accounts").getJSONObject(0).getLong("id"); return true; } setErrorMessage(lastResponse.getString("error")); } catch (IOException e) { setErrorMessage("Network Error"); return false; } return false; } public String getApiErrorMessage() { if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) { return "API key is empty."; } return error; } private void setErrorMessage(String message) { this.error = message; } private Project jsonToProject(JSONObject projectJson) { JSONObject projectInfo = new JSONObject(projectJson.getString("description")); Project project = CommonProjectFactory.create(projectJson.getLong("id"), projectJson.getString("name"), projectInfo.getString("description")); project.setLeader(projectInfo.getString("owner")); JSONArray members = projectInfo.getJSONArray("members"); for (int i = 0; i < members.length(); i++) { project.addNewMember(members.getString(i)); } JSONArray docks = projectJson.getJSONArray("dock"); long toDoPanelId = 0, messageBoardId = 0, scheduleId = 0; for (int j = 0; j < docks.length(); j++) { JSONObject dock = docks.getJSONObject(j); switch (dock.getString("name")) { case "message_board" -> messageBoardId = dock.getLong("id"); case "todoset" -> toDoPanelId = dock.getLong("id"); case "schedule" -> scheduleId = dock.getLong("id"); } }
package data_access; public abstract class HttpDataAccessObject implements SignupUserDataAccessInterface, LoginUserDataAccessInterface, ProjectUserDataAccessInterface, ChooseProjectUserDataAccessInterface, AddProjectUserDataAccessInterface, MessageBoardUserDataAccessInterface, AddToDoUserDataAccessInterface, ToDoListDataAccessInterface, AddToDoListUserDataAccessInterface, ToDoPanelDataAccessInterface, ScheduleDataAccessInterface { private final String API_KEY; private final OkHttpClient client = new OkHttpClient().newBuilder() .build(); private long orgId; private String error; public HttpDataAccessObject(String apiKey) throws InvalidApiKeyException { API_KEY = apiKey; if (!isValidApiKey()) { throw new InvalidApiKeyException(getApiErrorMessage()); } } private Request.Builder buildRequest() { return new Request.Builder() .addHeader("Authorization", "Bearer " + API_KEY) .addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("User-Agent", "TasksMaster ([email protected])"); } private boolean isValidApiKey() { if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) { return false; } Request request = buildRequest() .url("https://launchpad.37signals.com/authorization.json") .build(); try { Response response = client.newCall(request).execute(); if (response.code() != 200 || response.body() == null) { setErrorMessage("Network Error"); return false; } JSONObject lastResponse = new JSONObject(response.body().string()); if (!lastResponse.has("error")) { orgId = lastResponse.getJSONArray("accounts").getJSONObject(0).getLong("id"); return true; } setErrorMessage(lastResponse.getString("error")); } catch (IOException e) { setErrorMessage("Network Error"); return false; } return false; } public String getApiErrorMessage() { if (API_KEY == null || API_KEY.isEmpty() || API_KEY.isBlank()) { return "API key is empty."; } return error; } private void setErrorMessage(String message) { this.error = message; } private Project jsonToProject(JSONObject projectJson) { JSONObject projectInfo = new JSONObject(projectJson.getString("description")); Project project = CommonProjectFactory.create(projectJson.getLong("id"), projectJson.getString("name"), projectInfo.getString("description")); project.setLeader(projectInfo.getString("owner")); JSONArray members = projectInfo.getJSONArray("members"); for (int i = 0; i < members.length(); i++) { project.addNewMember(members.getString(i)); } JSONArray docks = projectJson.getJSONArray("dock"); long toDoPanelId = 0, messageBoardId = 0, scheduleId = 0; for (int j = 0; j < docks.length(); j++) { JSONObject dock = docks.getJSONObject(j); switch (dock.getString("name")) { case "message_board" -> messageBoardId = dock.getLong("id"); case "todoset" -> toDoPanelId = dock.getLong("id"); case "schedule" -> scheduleId = dock.getLong("id"); } }
project.setToDoPanel(CommonToDoPanelFactory.create(toDoPanelId));
25
2023-10-23 15:17:21+00:00
8k
denis-vp/toy-language-interpreter
src/main/java/view/cli/CliInterpreter.java
[ { "identifier": "Controller", "path": "src/main/java/controller/Controller.java", "snippet": "public class Controller {\n private final IRepository repository;\n private Boolean logOutput;\n private final ExecutorService executor = Executors.newFixedThreadPool(8);\n\n public Controller(IRepository repository, Boolean logOutput) {\n this.repository = repository;\n this.logOutput = logOutput;\n this.skipInitialCompoundStatementUnpacking();\n }\n\n public IRepository getRepository() {\n return this.repository;\n }\n\n public ExecutorService getExecutor() {\n return this.executor;\n }\n\n private void skipInitialCompoundStatementUnpacking() {\n boolean aux = logOutput;\n logOutput = false;\n\n List<ProgramState> programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n\n while (!programStates.isEmpty()) {\n IStack<Statement> executionStack = programStates.get(0).getExecutionStack();\n try {\n if (!(executionStack.top() instanceof CompoundStatement)) {\n break;\n }\n } catch (ADTException e) {\n throw new RuntimeException(e);\n }\n\n this.repository.getHeap().setContent(\n this.garbageCollector(\n this.getAddressesFromSymbolTable(this.repository.getSymbolTable().values()),\n this.repository.getHeap().getContent()\n ));\n\n try {\n this.oneStepForAllPrograms(programStates);\n } catch (RuntimeException | ControllerException e) {\n throw new RuntimeException(e);\n }\n\n programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n }\n\n this.repository.setProgramStateList(programStates);\n\n logOutput = aux;\n }\n\n public void oneStepForAllPrograms(List<ProgramState> programStates) throws ControllerException {\n List<Callable<ProgramState>> callList = programStates.stream()\n .map((ProgramState programState) -> (Callable<ProgramState>) programState::oneStep)\n .toList();\n\n try {\n List<ProgramState> newProgramStates = this.executor.invokeAll(callList).stream()\n .map(future -> {\n try {\n return future.get();\n } catch (InterruptedException | ExecutionException e) {\n throw new RuntimeException(e);\n }\n })\n .filter(Objects::nonNull)\n .toList();\n programStates.addAll(newProgramStates);\n } catch (InterruptedException e) {\n throw new ControllerException(e.getMessage());\n }\n\n if (this.logOutput) {\n programStates.forEach(programState -> {\n try {\n this.repository.logProgramStateExecution(programState);\n } catch (RepositoryException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n this.repository.setProgramStateList(programStates);\n }\n\n public void allSteps() throws ControllerException {\n List<ProgramState> programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n if (this.logOutput) {\n programStates.forEach(programState -> {\n try {\n this.repository.logProgramStateExecution(programState);\n } catch (RepositoryException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n while (!programStates.isEmpty()) {\n this.repository.getHeap().setContent(\n this.garbageCollector(\n this.getAddressesFromSymbolTable(this.repository.getSymbolTable().values()),\n this.repository.getHeap().getContent()\n ));\n\n try {\n this.oneStepForAllPrograms(programStates);\n } catch (RuntimeException e) {\n throw new ControllerException(e.getMessage());\n }\n\n programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n }\n\n this.executor.shutdownNow();\n this.repository.setProgramStateList(programStates);\n }\n\n public List<ProgramState> removeCompletedPrograms(List<ProgramState> programStates) {\n return programStates.stream()\n .filter(ProgramState::isNotCompleted)\n .collect(Collectors.toList());\n }\n\n public Map<Integer, Value> garbageCollector(List<Integer> symbolTableAddresses, Map<Integer, Value> heap) {\n return heap.entrySet().stream()\n .filter(entry -> {\n for (Value value : heap.values()) {\n if (value instanceof ReferenceValue referenceValue) {\n if (referenceValue.getAddress() == entry.getKey()) {\n return true;\n }\n }\n }\n return symbolTableAddresses.contains(entry.getKey());\n })\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n }\n\n public List<Integer> getAddressesFromSymbolTable(Collection<Value> symbolTableValues) {\n return symbolTableValues.stream()\n .filter(value -> value instanceof ReferenceValue)\n .map(value -> ((ReferenceValue) value).getAddress())\n .toList();\n }\n}" }, { "identifier": "ProgramGenerator", "path": "src/main/java/programgenerator/ProgramGenerator.java", "snippet": "public class ProgramGenerator {\n public static List<Statement> getPrograms() {\n ArrayList<Statement> programs = new ArrayList<>(\n Arrays.asList(\n ProgramGenerator.getProgram1(),\n ProgramGenerator.getProgram2(),\n ProgramGenerator.getProgram3(),\n ProgramGenerator.getProgram4(),\n ProgramGenerator.getProgram5(),\n ProgramGenerator.getProgram6(),\n ProgramGenerator.getProgram7(),\n ProgramGenerator.getProgram8(),\n ProgramGenerator.getProgram9()\n ));\n\n for (int i = 0; i < programs.size(); i++) {\n try {\n IDictionary<String, Type> typeEnvironment = new MyDictionary<>();\n programs.get(i).typeCheck(typeEnvironment);\n } catch (StatementException e) {\n System.out.println(e.getMessage());\n programs.remove(i);\n i--;\n }\n }\n\n return programs;\n }\n\n private static Statement buildProgram(Statement... statements) {\n if (statements.length == 0) {\n return new NopStatement();\n } else if (statements.length == 1) {\n return statements[0];\n }\n\n Statement example = new CompoundStatement(statements[0], statements[1]);\n for (int i = 2; i < statements.length; i++) {\n example = new CompoundStatement(example, statements[i]);\n }\n\n return example;\n }\n\n private static Statement getProgram1() {\n// Basic Example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(2)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, printingV);\n }\n\n private static Statement getProgram2() {\n// Arithmetic expressions example\n Statement declaringA = new VarDecStatement(\"a\", new IntType());\n Statement declaringB = new VarDecStatement(\"b\", new IntType());\n Statement assigningA = new AssignmentStatement(\"a\",\n new ArithmeticExpression(\"+\", new ValueExpression(new IntValue(2)),\n new ArithmeticExpression(\"*\", new ValueExpression(new IntValue(3)),\n new ValueExpression(new IntValue(5)))));\n Statement assigningB = new AssignmentStatement(\"b\",\n new ArithmeticExpression(\"+\", new VarNameExpression(\"a\"),\n new ValueExpression(new IntValue(1))));\n Statement printingB = new PrintStatement(new VarNameExpression(\"b\"));\n\n return ProgramGenerator.buildProgram(declaringA, declaringB, assigningA, assigningB, printingB);\n }\n\n private static Statement getProgram3() {\n// If statement example\n Statement declaringA = new VarDecStatement(\"a\", new BoolType());\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningA = new AssignmentStatement(\"a\", new ValueExpression(new BoolValue(true)));\n Statement ifStatement = new IfStatement(new VarNameExpression(\"a\"),\n new AssignmentStatement(\"v\", new ValueExpression(new IntValue(2))),\n new AssignmentStatement(\"v\", new ValueExpression(new IntValue(3))));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringA, declaringV, assigningA, ifStatement, printingV);\n }\n\n private static Statement getProgram4() {\n// File handling example\n Statement declaringV = new VarDecStatement(\"v\", new StringType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new StringValue(\"./input/test.in\")));\n Statement openingFile = new OpenFileStatement(new VarNameExpression(\"v\"));\n Statement declaringC = new VarDecStatement(\"c\", new IntType());\n Statement readingC = new FileReadStatement(new VarNameExpression(\"v\"), \"c\");\n Statement printingC = new PrintStatement(new VarNameExpression(\"c\"));\n Statement closingFile = new CloseFileReadStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, openingFile, declaringC, readingC,\n printingC, readingC, printingC, closingFile);\n }\n\n private static Statement getProgram5() {\n// Relational expressions example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(1)));\n Statement ifStatement = new IfStatement(new RelationalExpression(\"<\", new VarNameExpression(\"v\"), new ValueExpression(new IntValue(3))),\n new PrintStatement(new VarNameExpression(\"v\")),\n new NopStatement());\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, ifStatement);\n }\n\n private static Statement getProgram6() {\n// Heap handling example\n Statement declaringV = new VarDecStatement(\"v\", new ReferenceType(new IntType()));\n Statement allocatingV = new HeapAllocationStatement(\"v\", new ValueExpression(new IntValue(20)));\n Statement declaringA = new VarDecStatement(\"a\", new ReferenceType(new ReferenceType(new IntType())));\n Statement allocatingA = new HeapAllocationStatement(\"a\", new VarNameExpression(\"v\"));\n Statement allocatingV2 = new HeapAllocationStatement(\"v\", new ValueExpression(new IntValue(30)));\n Statement printingA = new PrintStatement(new HeapReadExpression(new HeapReadExpression(new VarNameExpression(\"a\"))));\n Statement declaringG = new VarDecStatement(\"g\", new ReferenceType(new IntType()));\n Statement allocatingG = new HeapAllocationStatement(\"g\", new ValueExpression(new IntValue(5)));\n Statement allocatingG2 = new HeapAllocationStatement(\"g\", new ValueExpression(new IntValue(10)));\n Statement printingG = new PrintStatement(new HeapReadExpression(new VarNameExpression(\"g\")));\n\n return ProgramGenerator.buildProgram(declaringV, allocatingV, declaringA, allocatingA,\n allocatingV2, printingA, declaringG, allocatingG, allocatingG2, printingG);\n }\n\n private static Statement getProgram7() {\n// While statement example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(4)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n Statement decrementingV = new AssignmentStatement(\"v\", new ArithmeticExpression(\"-\",\n new VarNameExpression(\"v\"), new ValueExpression(new IntValue(1))));\n Statement whileStatement = new WhileStatement(new RelationalExpression(\">\",\n new VarNameExpression(\"v\"), new ValueExpression(new IntValue(0))),\n new CompoundStatement(printingV, decrementingV));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, whileStatement);\n }\n\n private static Statement getProgram8() {\n// For statement example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(1)));\n Statement declaringAssigningI = new CompoundStatement(new VarDecStatement(\"i\", new IntType()),\n new AssignmentStatement(\"i\", new ValueExpression(new IntValue(2))));\n Statement incrementingI = new AssignmentStatement(\"i\", new ArithmeticExpression(\"+\",\n new VarNameExpression(\"i\"), new ValueExpression(new IntValue(1))));\n Statement multiplyingV = new AssignmentStatement(\"v\", new ArithmeticExpression(\"*\",\n new VarNameExpression(\"v\"), new VarNameExpression(\"i\")));\n Statement forStatement = new ForStatement(declaringAssigningI, new RelationalExpression(\"<\",\n new VarNameExpression(\"i\"), new ValueExpression(new IntValue(10))), incrementingI, multiplyingV);\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, forStatement, printingV);\n }\n\n private static Statement getProgram9() {\n// Threading example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement declaringA = new VarDecStatement(\"a\", new ReferenceType(new IntType()));\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(10)));\n Statement allocatingA = new HeapAllocationStatement(\"a\", new ValueExpression(new IntValue(22)));\n Statement writingA = new HeapWriteStatement(\"a\", new ValueExpression(new IntValue(30)));\n Statement assigningV2 = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(32)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n Statement printingA = new PrintStatement(new HeapReadExpression(new VarNameExpression(\"a\")));\n Statement thread1 = new ForkStatement(new CompoundStatement(writingA,\n new CompoundStatement(assigningV2, new CompoundStatement(printingV, printingA))));\n\n return ProgramGenerator.buildProgram(declaringV, declaringA, assigningV, allocatingA, thread1, printingV, printingA);\n }\n\n private static Statement getProgram10() {\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(10)));\n Statement thread1 = new ForkStatement(new ForkStatement(new PrintStatement(new VarNameExpression(\"v\"))));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, thread1, printingV);\n }\n}" }, { "identifier": "ProgramState", "path": "src/main/java/model/ProgramState.java", "snippet": "public class ProgramState {\n private final Statement originalProgram;\n private final IStack<Statement> executionStack;\n private final IDictionary<String, Value> symbolTable;\n private final IHeap heap;\n private final IDictionary<String, BufferedReader> fileTable;\n private final IList<Value> output;\n private final int id;\n private static final Set<Integer> ids = new HashSet<>();\n\n public ProgramState(Statement originalProgram,\n IStack<Statement> executionStack, IDictionary<String, Value> symbolTable,\n IHeap heap, IDictionary<String, BufferedReader> fileTable,\n IList<Value> output) {\n\n this.originalProgram = originalProgram.deepCopy();\n this.executionStack = executionStack;\n this.symbolTable = symbolTable;\n this.heap = heap;\n this.fileTable = fileTable;\n this.output = output;\n\n this.id = ProgramState.generateNewId();\n executionStack.push(originalProgram);\n }\n\n private static int generateNewId() {\n Random random = new Random();\n int id;\n synchronized (ProgramState.ids) {\n do {\n id = random.nextInt();\n } while (ProgramState.ids.contains(id));\n ProgramState.ids.add(id);\n }\n return id;\n }\n\n public int getId() {\n return this.id;\n }\n\n public Statement getOriginalProgram() {\n return this.originalProgram;\n }\n\n public IStack<Statement> getExecutionStack() {\n return this.executionStack;\n }\n\n public IDictionary<String, Value> getSymbolTable() {\n return this.symbolTable;\n }\n\n public IHeap getHeap() {\n return this.heap;\n }\n\n public IDictionary<String, BufferedReader> getFileTable() {\n return this.fileTable;\n }\n\n public IList<Value> getOutput() {\n return this.output;\n }\n\n public boolean isNotCompleted() {\n return !this.executionStack.isEmpty();\n }\n\n public ProgramState oneStep() throws ProgramStateException {\n if (this.executionStack.isEmpty()) {\n throw new ProgramStateException(\"Execution stack is empty!\");\n }\n\n try {\n Statement currentStatement = this.executionStack.pop();\n return currentStatement.execute(this);\n } catch (StatementException | ADTException e) {\n throw new ProgramStateException(e.getMessage());\n }\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"Program State: \").append(this.id).append(\"\\n\");\n stringBuilder.append(\"Execution Stack:\\n\");\n if (this.executionStack.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.executionStack);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Symbol Table:\\n\");\n if (this.symbolTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.symbolTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Heap:\\n\");\n if (this.heap.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.heap);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"File Table:\\n\");\n if (this.fileTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.fileTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Output:\\n\");\n if (this.output.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.output);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n\n return stringBuilder.toString();\n }\n}" }, { "identifier": "Statement", "path": "src/main/java/model/statement/Statement.java", "snippet": "public interface Statement {\n ProgramState execute(ProgramState state) throws StatementException;\n\n IDictionary<String, Type> typeCheck(IDictionary<String, Type> typeEnvironment) throws StatementException;\n\n Statement deepCopy();\n}" }, { "identifier": "IRepository", "path": "src/main/java/repository/IRepository.java", "snippet": "public interface IRepository {\n\n List<ProgramState> getProgramStateList();\n\n void setProgramStateList(List<ProgramState> programStateList);\n\n IHeap getHeap();\n\n IDictionary<String, Value> getSymbolTable();\n\n void logProgramStateExecution(ProgramState programState) throws RepositoryException;\n}" }, { "identifier": "Repository", "path": "src/main/java/repository/Repository.java", "snippet": "public class Repository implements IRepository {\n private final List<ProgramState> programStateList = new ArrayList<ProgramState>();\n private final String logFilePath;\n\n public Repository(ProgramState initialProgram, String logFilePath) {\n this.programStateList.add(initialProgram);\n this.logFilePath = logFilePath;\n }\n\n @Override\n public List<ProgramState> getProgramStateList() {\n return List.copyOf(this.programStateList);\n }\n\n @Override\n public void setProgramStateList(List<ProgramState> programStateList) {\n this.programStateList.clear();\n this.programStateList.addAll(programStateList);\n }\n\n @Override\n public IHeap getHeap() {\n return this.programStateList.get(0).getHeap();\n }\n\n @Override\n public IDictionary<String, Value> getSymbolTable() {\n return this.programStateList.get(0).getSymbolTable();\n }\n\n @Override\n public void logProgramStateExecution(ProgramState programState) throws RepositoryException {\n try (PrintWriter logFile = new PrintWriter(new BufferedWriter(new FileWriter(this.logFilePath, true)))) {\n logFile.println(programState);\n } catch (IOException e) {\n throw new RepositoryException(\"Could not open log file!\");\n }\n }\n}" }, { "identifier": "ExitCommand", "path": "src/main/java/view/cli/commands/ExitCommand.java", "snippet": "public class ExitCommand extends Command {\n public ExitCommand(String id, String description) {\n super(id, description);\n }\n\n @Override\n public void execute() {\n System.exit(0);\n }\n}" }, { "identifier": "RunExampleCommand", "path": "src/main/java/view/cli/commands/RunExampleCommand.java", "snippet": "public class RunExampleCommand extends Command {\n private final Controller controller;\n\n public RunExampleCommand(String id, String description, Controller controller) {\n super(id, description);\n this.controller = controller;\n }\n\n @Override\n public void execute() {\n try {\n this.controller.allSteps();\n } catch (InterpreterException e) {\n System.out.println(\"Something went wrong! \" + e.getMessage());\n }\n }\n}" } ]
import adt.*; import controller.Controller; import programgenerator.ProgramGenerator; import model.ProgramState; import model.statement.Statement; import repository.IRepository; import repository.Repository; import view.cli.commands.ExitCommand; import view.cli.commands.RunExampleCommand; import java.util.List; import java.util.Objects; import java.util.Scanner;
5,195
package view.cli; public class CliInterpreter { public static void main(String[] args) { TextMenu menu = new TextMenu(); CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu); menu.show(); } private static String getLogFile() { String logFilePath = "./logs/"; Scanner scanner = new Scanner(System.in); System.out.print("Please enter the log file name: "); String input = scanner.nextLine(); if (Objects.equals(input, "")) { logFilePath += "log.txt"; } else { logFilePath += input; } return logFilePath; } private static void addCommands(String logFilePath, TextMenu menu) { List<Statement> programs = ProgramGenerator.getPrograms(); for (int i = 0; i < programs.size(); i++) { Statement program = programs.get(i); ProgramState programState = new ProgramState(program, new MyStack<>(), new MyDictionary<>(), new MyHeap(), new MyConcurrentDictionary<>(), new MyList<>()); IRepository repository = new Repository(programState, logFilePath); Controller controller = new Controller(repository, true);
package view.cli; public class CliInterpreter { public static void main(String[] args) { TextMenu menu = new TextMenu(); CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu); menu.show(); } private static String getLogFile() { String logFilePath = "./logs/"; Scanner scanner = new Scanner(System.in); System.out.print("Please enter the log file name: "); String input = scanner.nextLine(); if (Objects.equals(input, "")) { logFilePath += "log.txt"; } else { logFilePath += input; } return logFilePath; } private static void addCommands(String logFilePath, TextMenu menu) { List<Statement> programs = ProgramGenerator.getPrograms(); for (int i = 0; i < programs.size(); i++) { Statement program = programs.get(i); ProgramState programState = new ProgramState(program, new MyStack<>(), new MyDictionary<>(), new MyHeap(), new MyConcurrentDictionary<>(), new MyList<>()); IRepository repository = new Repository(programState, logFilePath); Controller controller = new Controller(repository, true);
menu.addCommand(new RunExampleCommand(String.valueOf(i + 1), "run example " + (i + 1), controller));
7
2023-10-21 18:08:59+00:00
8k
NewStudyGround/NewStudyGround
server/src/main/java/com/codestates/server/domain/comment/controller/CommentController.java
[ { "identifier": "Answer", "path": "server/src/main/java/com/codestates/server/domain/answer/entity/Answer.java", "snippet": "@Entity\n@Getter\n@Setter\npublic class Answer {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long answerId;\n\n\t@Column(length = 10000, nullable = false)\n\tprivate String content;\n\n\t@Column\n\tprivate LocalDateTime modifiedAt = LocalDateTime.now();\n\n\t@JoinColumn(name = \"board_Id\")\n\t@JsonIgnore\n\t@ManyToOne\n\tprivate Board board;\n\n\t@JoinColumn(name = \"member_Id\")\n\t@JsonIgnore\n\t@ManyToOne\n\tprivate Member member;\n\n\t@OneToMany(mappedBy = \"answer\", cascade = CascadeType.ALL)\n\tprivate List<Comment> comments;\n}" }, { "identifier": "AnswerService", "path": "server/src/main/java/com/codestates/server/domain/answer/service/AnswerService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class AnswerService {\n\n\tprivate final AnswerRepository answerRepository;\n\tprivate final BoardService boardService;\n\tprivate final BoardRepository boardRepository;\n\tprivate final MemberService memberService;\n\n\tpublic Answer createAnswer(Answer answer, Long boardId, Long memberId) {\n\t\t// 가입된 회원인지 검증하기\n\t\tMember getMember = memberService.getVerifiedMember(memberId);\n\n\t\tBoard board = boardRepository.findById(boardId).orElseThrow(() -> new BusinessLogicException(ExceptionCode.BOARD_NOT_FOUND));\n\t\tanswer.setBoard(board);\n\t\tanswer.setMember(getMember);\n\t\tanswerRepository.save(answer);\n\t\treturn answer;\n\t}\n\n\tpublic Answer updateAnswer(Answer answer, long boardId, long memberId) {\n\n\t\tBoard board = boardService.findBoard(boardId);\n\t\tAnswer existingAnswer = findAnswerById(answer.getAnswerId());\n\n\t\tif(existingAnswer != null) {\n\t\t\texistingAnswer.setContent(answer.getContent());\n\t\t\tanswerRepository.save(existingAnswer);\n\n\t\t\treturn existingAnswer;\n\t\t} else throw new BusinessLogicException(ExceptionCode.ANSWER_NOT_FOUND);\n\t}\n\n\tpublic List<Answer> findByBoardId(long boardId){\n\t\treturn answerRepository.findByBoardId(boardId);\n\t}\n\n\tpublic void deleteAnswer(long boardId, long answerId, long memberId) {\n\n\t\tmemberService.verifyAuthorizedUser(memberId);\n\t\tboardService.getBoard(boardId);\n\n\t\tAnswer existingAnswer = findAnswerById(answerId);\n\n\t\tif(existingAnswer != null) {\n\t\t\tif(existingAnswer.getBoard().getBoardId() == boardId) {\n\t\t\t\tanswerRepository.deleteById(answerId);\n\t\t\t} else throw new BusinessLogicException(ExceptionCode.BOARD_NOT_FOUND);\n\t\t}\n}\n\n\tpublic Answer findAnswerById(long answerId) {\n\t\treturn answerRepository.findById(answerId).orElseThrow(() -> new BusinessLogicException(ExceptionCode.ANSWER_NOT_FOUND));\n\t}\n\n}" }, { "identifier": "CommentPatchDto", "path": "server/src/main/java/com/codestates/server/domain/comment/dto/CommentPatchDto.java", "snippet": "@Getter\n@Setter\npublic class CommentPatchDto {\n\n private Member member;\n private Answer answer;\n\n @Positive\n private Long memberId;\n\n @NotBlank(message = \"답글을 수정해주세요.\")\n private String content;\n}" }, { "identifier": "CommentPostDto", "path": "server/src/main/java/com/codestates/server/domain/comment/dto/CommentPostDto.java", "snippet": "@Getter\n@Setter\npublic class CommentPostDto {\n\n private Member member;\n private Answer answer;\n\n @Positive\n private Long memberId;\n\n @NotBlank(message = \"답글을 작성해주세요.\")\n private String content;\n}" }, { "identifier": "Comment", "path": "server/src/main/java/com/codestates/server/domain/comment/entity/Comment.java", "snippet": "@Entity\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Getter\n@Setter\npublic class Comment {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column\n private String content;\n\n @ManyToOne\n @JoinColumn(name = \"member_Id\")\n @JsonIgnore\n private Member member;\n\n @ManyToOne\n @JoinColumn(name = \"answer_id\")\n @JsonIgnore\n private Answer answer;\n\n}" }, { "identifier": "CommentMapper", "path": "server/src/main/java/com/codestates/server/domain/comment/mapper/CommentMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface CommentMapper {\n\n /**\n * commentPostDto 를 Comment로 변환\n * @param commentPostDto\n * @return\n */\n default Comment commentPostDtoToComment(CommentPostDto commentPostDto){\n\n if (commentPostDto == null) {\n return null;\n } else {\n Comment comment = Comment.builder()\n .content(commentPostDto.getContent())\n .member(commentPostDto.getMember())\n .answer(commentPostDto.getAnswer())\n .build();\n return comment;\n }\n }\n\n /**\n * commentPatchDto 를 Comment로 변환\n * @param commentPatchDto\n * @return\n */\n default Comment commentPatchDtoToComment(CommentPatchDto commentPatchDto){\n\n if (commentPatchDto == null) {\n return null;\n } else {\n Comment comment = Comment.builder()\n .content(commentPatchDto.getContent())\n .member(commentPatchDto.getMember())\n .answer(commentPatchDto.getAnswer())\n .build();\n return comment;\n }\n }\n\n}" }, { "identifier": "CommentService", "path": "server/src/main/java/com/codestates/server/domain/comment/service/CommentService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class CommentService {\n\n private final CommentRepository commentRepository;\n private final MemberService memberService;\n\n /**\n * comment 등록\n * @param comment\n * @return\n */\n public Comment createComment(Comment comment) {\n\n return commentRepository.save(comment);\n }\n\n /**\n * comment 수정\n * @param comment\n * @return\n */\n public void updateComment(Comment comment) {\n\n Comment existComment = findCommentById(comment.getId());\n\n if(existComment != null){\n Comment updatedComment = commentRepository.save(comment);\n\n }else {\n throw new BusinessLogicException(ExceptionCode.COMMENT_NOT_FOUND);\n }\n }\n\n /**\n * comment 삭제\n * @param commentId\n * @param answerId\n * @param memberId\n */\n public void deleteComment(long commentId, long answerId, long memberId) {\n\n memberService.verifyAuthorizedUser(memberId);\n\n Comment existingComment = findCommentById(commentId);\n\n if (existingComment != null) {\n if (existingComment.getAnswer().getAnswerId() == answerId ) {\n commentRepository.deleteById(commentId);\n } else {\n throw new BusinessLogicException(ExceptionCode.ANSWER_NOT_FOUND);\n }\n }\n }\n\n /**\n * commentId를 통해서 commentRepo에서 존재하는지 검색을 한다.\n * @param commentId\n * @return\n */\n public Comment findCommentById(long commentId) {\n return commentRepository.findById(commentId).orElseThrow(()->new BusinessLogicException(ExceptionCode.COMMENT_NOT_FOUND));\n }\n}" }, { "identifier": "Member", "path": "server/src/main/java/com/codestates/server/domain/member/entity/Member.java", "snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\n@Entity\npublic class Member {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long memberId;\n\n private String email;\n\n private String name; // 닉네임\n\n private String phone;\n\n private String password;\n\n private String profileImage;\n\n // 멤버 당 하나의 권한을 가지기 때문에 즉시 로딩 괜찮음 (즉시로딩 N : 1은 괜찮으나 1:N은 안됨)\n // 사용자 등록 시 사용자의 권한 등록을 위해 권한 테이블 생성\n @ElementCollection(fetch = FetchType.EAGER)\n private List<String> roles = new ArrayList<>();\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Board> boards;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Answer> answers;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Comment> comments;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Bookmark> Bookmarks;\n\n}" }, { "identifier": "MemberService", "path": "server/src/main/java/com/codestates/server/domain/member/service/MemberService.java", "snippet": "@Service\n@AllArgsConstructor\n@Transactional\npublic class MemberService {\n\n private final MemberRepository memberRepository;\n private final BoardRepository boardRepository;\n\n private final PasswordEncoder passwordEncoder; // 비밀번호 암호화\n private final CustomAuthorityUtils customAuthorityUtils; // 사용자 권한 설정\n private final S3UploadService s3UploadService;\n private final ApplicationEventPublisher eventPublisher;\n\n private static final String DEFAULT_IMAGE = \"http://bit.ly/46a2mSp\"; // 회원 기본 이미지\n private static final String MEMBER_IMAGE_PROCESS_TYPE = \"profile-image\";\n\n /**\n * 회원 가입 로직\n * 존재하는 회원인지 확인한다.\n *\n * @param member\n * @return\n */\n public Member createMember(Member member) {\n\n // 가입된 이메일인지 확인\n verifiyExistedMember(member.getEmail());\n\n // 비밀번호 암호화\n String encrpytedPassword = passwordEncoder.encode(member.getPassword());\n member.setPassword(encrpytedPassword);\n\n // 이메일로 사용자 역할 DB에 저장\n List<String> roles;\n roles = customAuthorityUtils.createRoles(member.getEmail());\n member.setRoles(roles);\n\n if(member.getProfileImage() == null) {\n member.setProfileImage(DEFAULT_IMAGE);\n } else {\n member.setProfileImage(member.getProfileImage());\n }\n\n // 예외 발생 안 시키면 저장\n Member savedMember = memberRepository.save(member);\n\n MemberRegistrationEvent event = new MemberRegistrationEvent(member);\n eventPublisher.publishEvent(event);\n\n return savedMember;\n }\n\n public Member updateMember(Member member){\n\n Member getMember = verifyAuthorizedUser(member.getMemberId());\n\n if(member.getName() != null ) { // 입력받은 닉네임이 null 이 아니면\n getMember.setName(member.getName()); // getMember 에 입력받은 name 대체 -> null 이면 유지\n }\n if(member.getPhone() != null) { // 입력받은 폰이 null이 아니면\n getMember.setPhone(member.getPhone()); // getMember에 입력받은 phone 대체\n }\n if(member.getPassword() != null) { // 입력받은 password null 이 아니면\n getMember.setPassword(passwordEncoder.encode(member.getPassword())); // getPassword에 입력받은 password 대체 -> 인코딩\n }\n\n // 필드가 모두 null인 경우 예외 처리\n if(member.getName() == null && member.getPhone() == null && member.getPassword() == null) {\n throw new RuntimeException(\"수정할 정보가 없습니다.\");\n }\n\n return memberRepository.save(getMember);\n }\n\n public String uploadImage(Long memberId, MultipartFile file) {\n// public String uploadImage(Long memberId, MultipartFile file, int x, int y, int width, int height) throws IOException {\n\n Member member = verifyAuthorizedUser(memberId);\n\n // 현재 프로필 이미지 가지고 오기\n String presentProfileImage = member.getProfileImage();\n // 만약에 현재 파일이 있으면 현재 파일 삭제\n if (presentProfileImage != null && !presentProfileImage.equals(DEFAULT_IMAGE)) {\n s3UploadService.deleteImageFromS3(presentProfileImage, MEMBER_IMAGE_PROCESS_TYPE);\n// s3UploadService.deleteImageFromS3(presentProfileImage);\n }\n // profileImage 새로운 imgae로 upload 하기\n String newProfileImage = null;\n newProfileImage = s3UploadService.uploadProfileImage(file, MEMBER_IMAGE_PROCESS_TYPE);\n\n if(newProfileImage == null) {\n // 새로운 파일 업로드 하는 메서드 (파일, x좌표, y좌표, 가로, 세로)\n newProfileImage = DEFAULT_IMAGE;\n // newProfileImage = s3UploadService.uploadProfileImage(file, x, y, width, height);\n }\n // 회원 profileImage에 set 하고 save\n member.setProfileImage(newProfileImage);\n // 새로운 이미지 URL을 멤버 객체에 설정\n member.setProfileImage(newProfileImage);\n\n // 회원 정보 업데이트\n memberRepository.save(member);\n\n return newProfileImage;\n }\n\n public String deleteProfileImage(Long memberId) {\n\n Member member = verifyAuthorizedUser(memberId);\n\n // 현재 프로필 이미지 URL을 가져옵니다.\n String currentProfileImage = member.getProfileImage();\n\n // S3에서 현재 이미지 삭제\n if (currentProfileImage != null && !currentProfileImage.equals(DEFAULT_IMAGE)) {\n s3UploadService.deleteImageFromS3(currentProfileImage, MEMBER_IMAGE_PROCESS_TYPE);\n// s3UploadService.deleteImageFromS3(currentProfileImage);\n }\n\n // DB에서 프로필 이미지 URL 기본 설정\n member.setProfileImage(DEFAULT_IMAGE);\n memberRepository.save(member);\n\n return DEFAULT_IMAGE;\n }\n\n // member 마이페이지에서 사용자 정보 가지고 오는 메서드\n public Member getMember(Long memberId) {\n Member member = getVerifiedMember(memberId);\n\n return member;\n }\n\n // member 전체 정보 가지고 오는 메서드로 pagination\n public Page<Member> getMembers(int page, int size) {\n return memberRepository.findAll(PageRequest.of(page, size,\n Sort.by(\"memberId\").descending()));\n }\n\n // member 삭제하는 deleteMember 메서드\n public void deleteMember(Long memberId) {\n\n Member member = getVerifiedMember(memberId);\n\n memberRepository.delete(member);\n\n }\n\n /**\n * 등록된 회원인지 확인 (로그인 안 했으면 사용 불가)\n *\n * @param memberId\n * @return\n */\n public Member getVerifiedMember(Long memberId) {\n\n Optional<Member> member = memberRepository.findById(memberId);\n\n // 회원이 아니면 예외 발생\n Member getMember =\n member.orElseThrow(() -> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n\n return getMember;\n }\n\n\n /**\n * 이미 가입한 회원인지 확인하는 메서드\n * 만약 가입 되어있으면 예외 던지기\n * @param email\n */\n private void verifiyExistedMember(String email) {\n\n Optional<Member> optionalMember = memberRepository.findByEmail(email);\n\n if(optionalMember.isPresent())\n throw new BusinessLogicException(ExceptionCode.USER_EXISTS);\n }\n\n /**\n * 로그인한 Member를 가지고 오는 메서드\n * @return\n */\n public Member getLoginMember() {\n return memberRepository.findByEmail(AuthUserUtils.getAuthUser().getName())\n .orElseThrow(()-> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n }\n\n public Long getLoginMemberId(){\n\n try {\n Member member = memberRepository.findByEmail(AuthUserUtils.getAuthUser().getName()).orElseThrow(() ->\n new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n Long memberId = member.getMemberId();\n return memberId;\n\n }catch (Exception e){\n return 0L;\n }\n }\n\n public Member findMember(Long memberId){\n Member member = memberRepository.findById(memberId).orElseThrow(\n () -> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n return member;\n }\n\n /**\n * 현재 멤버 아이디랑 로그인한 객체의 아이디랑 비교해서 같은지 확인하는 메서드\n * @param memberId\n */\n public Member verifyAuthorizedUser(Long memberId) {\n Member getMember = getVerifiedMember(memberId);\n\n if (!getLoginMember().getMemberId().equals(memberId)) {\n throw new BusinessLogicException(ExceptionCode.UNAUTHORIZED_USER);\n }\n return getMember;\n }\n}" }, { "identifier": "UriCreator", "path": "server/src/main/java/com/codestates/server/global/uri/UriCreator.java", "snippet": "public class UriCreator {\n // URI 를 만드는 createUri 메서드\n public static URI createUri(String defaultUri, Long resourceId) {\n return UriComponentsBuilder\n .newInstance()\n .path(defaultUri + \"/{resourceId}\")// URI 경로 설정, resourceId 변수에는 값을 대체\n .buildAndExpand(resourceId) // 경로 변수를 실제 값으로 대체해서 URI 생성\n .toUri(); // 최종 URI로 변환하여 반환합니다.\n }\n}" } ]
import com.codestates.server.domain.answer.entity.Answer; import com.codestates.server.domain.answer.service.AnswerService; import com.codestates.server.domain.comment.dto.CommentPatchDto; import com.codestates.server.domain.comment.dto.CommentPostDto; import com.codestates.server.domain.comment.entity.Comment; import com.codestates.server.domain.comment.mapper.CommentMapper; import com.codestates.server.domain.comment.service.CommentService; import com.codestates.server.domain.member.entity.Member; import com.codestates.server.domain.member.service.MemberService; import com.codestates.server.global.uri.UriCreator; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.util.Map;
4,480
package com.codestates.server.domain.comment.controller; @RestController @RequestMapping("/answers/{answer-id}/comments") @RequiredArgsConstructor public class CommentController { private final CommentService commentService; private final MemberService memberService;
package com.codestates.server.domain.comment.controller; @RestController @RequestMapping("/answers/{answer-id}/comments") @RequiredArgsConstructor public class CommentController { private final CommentService commentService; private final MemberService memberService;
private final AnswerService answerService;
1
2023-10-23 09:41:00+00:00
8k
metacosm/quarkus-power
runtime/src/main/java/io/quarkiverse/power/runtime/sensors/macos/powermetrics/MacOSPowermetricsSensor.java
[ { "identifier": "PowerMeasure", "path": "runtime/src/main/java/io/quarkiverse/power/runtime/PowerMeasure.java", "snippet": "public interface PowerMeasure extends SensorMeasure {\n int numberOfSamples();\n\n long duration();\n\n default double average() {\n return total() / numberOfSamples();\n }\n\n double[] averagesPerComponent();\n\n double minMeasuredTotal();\n\n double maxMeasuredTotal();\n\n default double standardDeviation() {\n final var cardinality = metadata().componentCardinality();\n final var samples = numberOfSamples() - 1; // unbiased so we remove one sample\n // need to compute the average of variances then square root that to get the \"aggregate\" standard deviation, see: https://stats.stackexchange.com/a/26647\n // \"vectorize\" computation of variances: compute the variance for each component in parallel\n final var componentVarianceAverage = IntStream.range(0, cardinality).parallel()\n // compute variances for each component of the measure\n .mapToDouble(component -> {\n final var squaredDifferenceSum = measures().stream().parallel()\n .mapToDouble(m -> Math.pow(m[component] - averagesPerComponent()[component], 2))\n .sum();\n return squaredDifferenceSum / samples;\n })\n .average()\n .orElse(0.0);\n return Math.sqrt(componentVarianceAverage);\n }\n\n static String asString(PowerMeasure measure) {\n final var durationInSeconds = measure.duration() / 1000;\n final var samples = measure.numberOfSamples();\n final var measuredMilliWatts = measure.total();\n return String.format(\"%s / avg: %s / std dev: %.3f [min: %.3f, max: %.3f] (%ds, %s samples)\",\n readableWithUnit(measuredMilliWatts),\n readableWithUnit(measure.average()), measure.standardDeviation(), measure.minMeasuredTotal(),\n measure.maxMeasuredTotal(), durationInSeconds,\n samples);\n }\n\n static String readableWithUnit(double milliWatts) {\n String unit = milliWatts >= 1000 ? \"W\" : \"mW\";\n double power = milliWatts >= 1000 ? milliWatts / 1000 : milliWatts;\n return String.format(\"%.3f%s\", power, unit);\n }\n\n List<double[]> measures();\n}" }, { "identifier": "PowerMeasurer", "path": "runtime/src/main/java/io/quarkiverse/power/runtime/PowerMeasurer.java", "snippet": "public class PowerMeasurer<M extends SensorMeasure> {\n private static final OperatingSystemMXBean osBean;\n\n static {\n osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n // take two measures to avoid initial zero values\n osBean.getProcessCpuLoad();\n osBean.getCpuLoad();\n osBean.getProcessCpuLoad();\n osBean.getCpuLoad();\n }\n\n private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();\n private ScheduledFuture<?> scheduled;\n private final PowerSensor<M> sensor;\n private OngoingPowerMeasure measure;\n\n private Consumer<PowerMeasure> completed;\n private BiConsumer<Integer, PowerMeasure> sampled;\n private Consumer<Exception> errorHandler;\n\n private final static PowerMeasurer<? extends SensorMeasure> instance = new PowerMeasurer<>(\n PowerSensorProducer.determinePowerSensor());\n\n public static PowerMeasurer<? extends SensorMeasure> instance() {\n return instance;\n }\n\n public PowerMeasurer(PowerSensor<M> sensor) {\n this.sensor = sensor;\n this.onError(null);\n }\n\n public double cpuShareOfJVMProcess() {\n final var processCpuLoad = osBean.getProcessCpuLoad();\n final var cpuLoad = osBean.getCpuLoad();\n return (processCpuLoad < 0 || cpuLoad <= 0) ? 0 : processCpuLoad / cpuLoad;\n }\n\n public void onCompleted(Consumer<PowerMeasure> completed) {\n this.completed = completed;\n }\n\n public void onSampled(BiConsumer<Integer, PowerMeasure> sampled) {\n this.sampled = sampled;\n }\n\n public void onError(Consumer<Exception> errorHandler) {\n this.errorHandler = errorHandler != null ? errorHandler : (exception) -> {\n throw new RuntimeException(exception);\n };\n }\n\n public Optional<String> additionalSensorInfo() {\n return Optional.ofNullable(measure).flatMap(sensor::additionalInfo);\n }\n\n public boolean isRunning() {\n return measure != null;\n }\n\n public void start(long durationInSeconds, long frequencyInMilliseconds)\n throws Exception {\n try {\n measure = sensor.start(durationInSeconds, frequencyInMilliseconds);\n\n if (durationInSeconds > 0) {\n executor.schedule(this::stop, durationInSeconds, TimeUnit.SECONDS);\n }\n\n scheduled = executor.scheduleAtFixedRate(this::update, 0, frequencyInMilliseconds, TimeUnit.MILLISECONDS);\n } catch (Exception e) {\n handleError(e);\n }\n }\n\n private void update() {\n try {\n sensor.update(measure);\n if (this.sampled != null) {\n sampled.accept(measure.numberOfSamples(), measure);\n }\n } catch (Exception e) {\n handleError(e);\n }\n }\n\n private void handleError(Exception e) {\n errorHandler.accept(e);\n try {\n if (scheduled != null) {\n scheduled.cancel(true);\n }\n if (sensor != null) {\n sensor.stop();\n }\n } catch (Exception ex) {\n // ignore shutting down exceptions\n }\n }\n\n public void stop() {\n try {\n if (isRunning()) {\n sensor.stop();\n scheduled.cancel(true);\n // record the result\n final var measured = new StoppedPowerMeasure(measure);\n // then set the measure to null to mark that we're ready for a new measure\n measure = null;\n // and finally, but only then, run the completion handler\n completed.accept(measured);\n }\n } catch (Exception e) {\n handleError(e);\n }\n }\n}" }, { "identifier": "OngoingPowerMeasure", "path": "runtime/src/main/java/io/quarkiverse/power/runtime/sensors/OngoingPowerMeasure.java", "snippet": "public class OngoingPowerMeasure extends AbstractPowerMeasure {\n private final long startedAt;\n private double minTotal = Double.MAX_VALUE;\n private double maxTotal;\n private final double[] totals;\n private double[] current;\n\n public OngoingPowerMeasure(SensorMetadata sensorMetadata, long duration, long frequency) {\n super(sensorMetadata, new ArrayList<>((int) (duration / frequency)));\n startedAt = System.currentTimeMillis();\n final var numComponents = metadata().componentCardinality();\n totals = new double[numComponents];\n }\n\n public void startNewMeasure() {\n if (current != null) {\n throw new IllegalStateException(\"A new measure cannot be started while one is still ongoing\");\n }\n current = new double[metadata().componentCardinality()];\n }\n\n public void setComponent(int index, double value) {\n if (current == null) {\n throw new IllegalStateException(\"A new measure must be started before recording components\");\n }\n current[index] = value;\n totals[index] += value;\n }\n\n public double[] stopMeasure() {\n if (current == null) {\n throw new IllegalStateException(\"Measure was not started so cannot be stopped\");\n }\n final var recorded = new double[current.length];\n System.arraycopy(current, 0, recorded, 0, current.length);\n measures().add(recorded);\n\n // record min / max totals\n final var recordedTotal = sumOfComponents(recorded);\n if (recordedTotal < minTotal) {\n minTotal = recordedTotal;\n }\n if (recordedTotal > maxTotal) {\n maxTotal = recordedTotal;\n }\n\n current = null;\n return recorded;\n }\n\n @Override\n public double total() {\n return sumOfComponents(totals);\n }\n\n public long duration() {\n return System.currentTimeMillis() - startedAt;\n }\n\n @Override\n public double minMeasuredTotal() {\n return minTotal;\n }\n\n @Override\n public double maxMeasuredTotal() {\n return maxTotal;\n }\n\n @Override\n public double[] averagesPerComponent() {\n return Arrays.stream(totals).map(total -> total / numberOfSamples()).toArray();\n }\n}" }, { "identifier": "PowerSensor", "path": "runtime/src/main/java/io/quarkiverse/power/runtime/sensors/PowerSensor.java", "snippet": "public interface PowerSensor<T extends SensorMeasure> {\n\n OngoingPowerMeasure start(long duration, long frequency) throws Exception;\n\n default void stop() {\n }\n\n void update(OngoingPowerMeasure ongoingMeasure);\n\n default Optional<String> additionalInfo(PowerMeasure measure) {\n return Optional.empty();\n }\n\n T measureFor(double[] measureComponents);\n}" }, { "identifier": "AppleSiliconMeasure", "path": "runtime/src/main/java/io/quarkiverse/power/runtime/sensors/macos/AppleSiliconMeasure.java", "snippet": "public class AppleSiliconMeasure implements SensorMeasure {\n private final double cpu;\n private final double gpu;\n private final double ane;\n public static final String ANE = \"ane\";\n public static final String CPU = \"cpu\";\n public static final String GPU = \"gpu\";\n public static final SensorMetadata METADATA = new SensorMetadata() {\n @Override\n public int indexFor(String component) {\n return switch (component) {\n case CPU -> 0;\n case GPU -> 1;\n case ANE -> 2;\n default -> throw new IllegalArgumentException(\"Unknown component: \" + component);\n };\n }\n\n @Override\n public int componentCardinality() {\n return 3;\n }\n };\n\n public AppleSiliconMeasure(double[] components) {\n this.cpu = components[METADATA.indexFor(CPU)];\n this.gpu = components[METADATA.indexFor(GPU)];\n this.ane = components[METADATA.indexFor(ANE)];\n }\n\n @Override\n public double total() {\n return cpu + gpu + ane;\n }\n\n @Override\n public SensorMetadata metadata() {\n return METADATA;\n }\n\n public double cpu() {\n return cpu;\n }\n}" } ]
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Optional; import io.quarkiverse.power.runtime.PowerMeasure; import io.quarkiverse.power.runtime.PowerMeasurer; import io.quarkiverse.power.runtime.sensors.OngoingPowerMeasure; import io.quarkiverse.power.runtime.sensors.PowerSensor; import io.quarkiverse.power.runtime.sensors.macos.AppleSiliconMeasure;
3,694
package io.quarkiverse.power.runtime.sensors.macos.powermetrics; public class MacOSPowermetricsSensor implements PowerSensor<AppleSiliconMeasure> { private Process powermetrics; private final static String pid = " " + ProcessHandle.current().pid() + " "; private double accumulatedCPUShareDiff = 0.0; private final int cpu; private final int gpu; private final int ane; public MacOSPowermetricsSensor() { ane = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.ANE); cpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.CPU); gpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.GPU); } private static class ProcessRecord { final double cpu; final double gpu; public ProcessRecord(String line) { //Name ID CPU ms/s samp ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s //iTerm2 1008 46.66 46.91 83.94 0.00 0.00 30.46 0.00 0.00 final var processData = line.split("\\s+"); cpu = Double.parseDouble(processData[3]); gpu = Double.parseDouble(processData[9]); } } @Override public void update(OngoingPowerMeasure ongoingMeasure) { extractPowerMeasure(ongoingMeasure, powermetrics.getInputStream(), pid, false); } AppleSiliconMeasure extractPowerMeasure(InputStream powerMeasureInput, long pid) { // one measure only return extractPowerMeasure(new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, 1, 1), powerMeasureInput, " " + pid + " ", true); } AppleSiliconMeasure extractPowerMeasure(OngoingPowerMeasure ongoingMeasure, InputStream powerMeasureInput, String paddedPIDAsString, boolean returnCurrent) { try { // Should not be closed since it closes the process BufferedReader input = new BufferedReader(new InputStreamReader(powerMeasureInput)); String line; double cpuShare = -1, gpuShare = -1; boolean totalDone = false; boolean cpuDone = false; // start measure ongoingMeasure.startNewMeasure(); while ((line = input.readLine()) != null) { if (line.isEmpty() || line.startsWith("*")) { continue; } // first, look for process line detailing share if (cpuShare < 0) { if (line.contains(paddedPIDAsString)) { final var procInfo = new ProcessRecord(line); cpuShare = procInfo.cpu; gpuShare = procInfo.gpu; } continue; } if (!totalDone) { // then skip all lines until we get the totals if (line.startsWith("ALL_TASKS")) { final var totals = new ProcessRecord(line); // compute ratio cpuShare = cpuShare / totals.cpu; gpuShare = totals.gpu > 0 ? gpuShare / totals.gpu : 0; totalDone = true; } continue; } if (!cpuDone) { // look for line that contains CPU power measure if (line.startsWith("CPU Power")) { final var jmxCpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess(); ongoingMeasure.setComponent(cpu, extractAttributedMeasure(line, cpuShare)); accumulatedCPUShareDiff += (cpuShare - jmxCpuShare); cpuDone = true; } continue; } if (line.startsWith("GPU Power")) { ongoingMeasure.setComponent(gpu, extractAttributedMeasure(line, gpuShare)); continue; } if (line.startsWith("ANE Power")) { ongoingMeasure.setComponent(ane, extractAttributedMeasure(line, 1)); break; } } final var measure = ongoingMeasure.stopMeasure(); return returnCurrent ? new AppleSiliconMeasure(measure) : null; } catch (Exception exception) { throw new RuntimeException(exception); } } private static double extractAttributedMeasure(String line, double attributionRatio) { final var powerValue = line.split(":")[1]; final var powerInMilliwatts = powerValue.split("m")[0]; return Double.parseDouble(powerInMilliwatts) * attributionRatio; } @Override public OngoingPowerMeasure start(long duration, long frequency) throws Exception { // it takes some time for the external process in addition to the sampling time so adjust the sampling frequency to account for this so that at most one measure occurs during the sampling time window final var freq = Long.toString(frequency - 50); powermetrics = Runtime.getRuntime() .exec("sudo powermetrics --samplers cpu_power,tasks --show-process-samp-norm --show-process-gpu -i " + freq); accumulatedCPUShareDiff = 0.0; return new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, duration, frequency); } @Override public void stop() { powermetrics.destroy(); } @Override
package io.quarkiverse.power.runtime.sensors.macos.powermetrics; public class MacOSPowermetricsSensor implements PowerSensor<AppleSiliconMeasure> { private Process powermetrics; private final static String pid = " " + ProcessHandle.current().pid() + " "; private double accumulatedCPUShareDiff = 0.0; private final int cpu; private final int gpu; private final int ane; public MacOSPowermetricsSensor() { ane = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.ANE); cpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.CPU); gpu = AppleSiliconMeasure.METADATA.indexFor(AppleSiliconMeasure.GPU); } private static class ProcessRecord { final double cpu; final double gpu; public ProcessRecord(String line) { //Name ID CPU ms/s samp ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s //iTerm2 1008 46.66 46.91 83.94 0.00 0.00 30.46 0.00 0.00 final var processData = line.split("\\s+"); cpu = Double.parseDouble(processData[3]); gpu = Double.parseDouble(processData[9]); } } @Override public void update(OngoingPowerMeasure ongoingMeasure) { extractPowerMeasure(ongoingMeasure, powermetrics.getInputStream(), pid, false); } AppleSiliconMeasure extractPowerMeasure(InputStream powerMeasureInput, long pid) { // one measure only return extractPowerMeasure(new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, 1, 1), powerMeasureInput, " " + pid + " ", true); } AppleSiliconMeasure extractPowerMeasure(OngoingPowerMeasure ongoingMeasure, InputStream powerMeasureInput, String paddedPIDAsString, boolean returnCurrent) { try { // Should not be closed since it closes the process BufferedReader input = new BufferedReader(new InputStreamReader(powerMeasureInput)); String line; double cpuShare = -1, gpuShare = -1; boolean totalDone = false; boolean cpuDone = false; // start measure ongoingMeasure.startNewMeasure(); while ((line = input.readLine()) != null) { if (line.isEmpty() || line.startsWith("*")) { continue; } // first, look for process line detailing share if (cpuShare < 0) { if (line.contains(paddedPIDAsString)) { final var procInfo = new ProcessRecord(line); cpuShare = procInfo.cpu; gpuShare = procInfo.gpu; } continue; } if (!totalDone) { // then skip all lines until we get the totals if (line.startsWith("ALL_TASKS")) { final var totals = new ProcessRecord(line); // compute ratio cpuShare = cpuShare / totals.cpu; gpuShare = totals.gpu > 0 ? gpuShare / totals.gpu : 0; totalDone = true; } continue; } if (!cpuDone) { // look for line that contains CPU power measure if (line.startsWith("CPU Power")) { final var jmxCpuShare = PowerMeasurer.instance().cpuShareOfJVMProcess(); ongoingMeasure.setComponent(cpu, extractAttributedMeasure(line, cpuShare)); accumulatedCPUShareDiff += (cpuShare - jmxCpuShare); cpuDone = true; } continue; } if (line.startsWith("GPU Power")) { ongoingMeasure.setComponent(gpu, extractAttributedMeasure(line, gpuShare)); continue; } if (line.startsWith("ANE Power")) { ongoingMeasure.setComponent(ane, extractAttributedMeasure(line, 1)); break; } } final var measure = ongoingMeasure.stopMeasure(); return returnCurrent ? new AppleSiliconMeasure(measure) : null; } catch (Exception exception) { throw new RuntimeException(exception); } } private static double extractAttributedMeasure(String line, double attributionRatio) { final var powerValue = line.split(":")[1]; final var powerInMilliwatts = powerValue.split("m")[0]; return Double.parseDouble(powerInMilliwatts) * attributionRatio; } @Override public OngoingPowerMeasure start(long duration, long frequency) throws Exception { // it takes some time for the external process in addition to the sampling time so adjust the sampling frequency to account for this so that at most one measure occurs during the sampling time window final var freq = Long.toString(frequency - 50); powermetrics = Runtime.getRuntime() .exec("sudo powermetrics --samplers cpu_power,tasks --show-process-samp-norm --show-process-gpu -i " + freq); accumulatedCPUShareDiff = 0.0; return new OngoingPowerMeasure(AppleSiliconMeasure.METADATA, duration, frequency); } @Override public void stop() { powermetrics.destroy(); } @Override
public Optional<String> additionalInfo(PowerMeasure measure) {
0
2023-10-23 16:44:57+00:00
8k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/listener/PlayerInteractListener.java
[ { "identifier": "Miniaturise", "path": "src/main/java/de/leghast/miniaturise/Miniaturise.java", "snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n @Override\n public void onEnable() {\n ConfigManager.setupConfig(this);\n initialiseManagers();\n registerListeners();\n setCommands();\n setTabCompleters();\n }\n\n @Override\n public void onDisable() {\n saveConfig();\n }\n\n private void initialiseManagers(){\n miniatureManager = new MiniatureManager(this);\n regionManager = new RegionManager(this);\n settingsManager = new SettingsManager(this);\n }\n\n private void registerListeners(){\n Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(this), this);\n Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(this), this);\n Bukkit.getPluginManager().registerEvents(new InventoryClickListener(this), this);\n }\n\n private void setCommands(){\n getCommand(\"select\").setExecutor(new SelectCommand(this));\n getCommand(\"scale\").setExecutor(new ScaleCommand(this));\n getCommand(\"cut\").setExecutor(new CutCommand(this));\n getCommand(\"tools\").setExecutor(new ToolsCommand(this));\n getCommand(\"paste\").setExecutor(new PasteCommand(this));\n getCommand(\"tool\").setExecutor(new ToolCommand(this));\n getCommand(\"delete\").setExecutor(new DeleteCommand(this));\n getCommand(\"copy\").setExecutor(new CopyCommand(this));\n getCommand(\"position\").setExecutor(new PositionCommand(this));\n getCommand(\"clear\").setExecutor(new ClearCommand(this));\n getCommand(\"adjust\").setExecutor(new AdjustCommand(this));\n getCommand(\"rotate\").setExecutor(new RotateCommand(this));\n }\n\n public void setTabCompleters(){\n getCommand(\"position\").setTabCompleter(new PositionTabCompleter());\n getCommand(\"scale\").setTabCompleter(new ScaleTabCompleter());\n getCommand(\"tool\").setTabCompleter(new ToolTabCompleter());\n getCommand(\"rotate\").setTabCompleter(new RotateTabCompleter());\n }\n\n /**\n * @return The MiniatureManager instance\n */\n public MiniatureManager getMiniatureManager(){\n return miniatureManager;\n }\n\n /**\n * @return The RegionManager instance\n */\n public RegionManager getRegionManager(){\n return regionManager;\n }\n\n public SettingsManager getSettingsManager(){\n return settingsManager;\n }\n\n}" }, { "identifier": "PlacedMiniature", "path": "src/main/java/de/leghast/miniaturise/instance/miniature/PlacedMiniature.java", "snippet": "public class PlacedMiniature {\n\n private List<BlockDisplay> blockDisplays;\n private double blockSize;\n\n public PlacedMiniature(List<MiniatureBlock> blocks, Location origin) throws InvalidParameterException {\n if(!blocks.isEmpty()){\n blockDisplays = new ArrayList<>();\n blockSize = blocks.get(0).getSize();\n\n for(MiniatureBlock mb : blocks) {\n BlockDisplay bd;\n bd = (BlockDisplay) origin.getWorld().spawnEntity(new Location(\n origin.getWorld(),\n mb.getX() + ceil(origin.getX()),\n mb.getY() + ceil(origin.getY()),\n mb.getZ() + ceil(origin.getZ())),\n EntityType.BLOCK_DISPLAY);\n bd.setBlock(mb.getBlockData());\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n blockDisplays.add(bd);\n }\n }else{\n throw new InvalidParameterException(\"The miniature block list is empty\");\n }\n }\n\n public PlacedMiniature(List<BlockDisplay> blockDisplays) throws InvalidParameterException{\n this.blockDisplays = blockDisplays;\n if(!blockDisplays.isEmpty()){\n blockSize = blockDisplays.get(0).getTransformation().getScale().x;\n }else{\n throw new InvalidParameterException(\"The block display list is empty\");\n }\n }\n\n public void remove(){\n for(BlockDisplay bd : blockDisplays){\n bd.remove();\n }\n }\n\n public void scaleUp(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleUp(scale);\n rearrange(origin, miniature);\n blockSize *= scale;\n });\n }\n\n public void scaleDown(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleDown(scale);\n rearrange(origin, miniature);\n blockSize /= scale;\n });\n }\n\n private void rearrange(Location origin, Miniature miniature) {\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n for(int i = 0; i < getBlockCount(); i++){\n BlockDisplay bd = blockDisplays.get(i);\n MiniatureBlock mb = miniature.getBlocks().get(i);\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.teleport(new Location( bd.getWorld(),\n mb.getX() + origin.getX(),\n mb.getY() + origin.getY(),\n mb.getZ() + origin.getZ()));\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n });\n }\n });\n }\n\n public void rotate(Axis axis, float angle){\n Location origin = blockDisplays.get(0).getLocation();\n float finalAngle = (float) Math.toRadians(angle);\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n\n for(BlockDisplay bd : blockDisplays){\n\n Transformation transformation = bd.getTransformation();\n\n switch (axis){\n case X -> transformation.getLeftRotation().rotateX(finalAngle);\n case Y -> transformation.getLeftRotation().rotateY(finalAngle);\n case Z -> transformation.getLeftRotation().rotateZ(finalAngle);\n }\n\n Vector3f newPositionVector = getRotatedPosition(\n bd.getLocation().toVector().toVector3f(),\n origin.toVector().toVector3f(),\n axis,\n finalAngle\n );\n\n Location newLocation = new Location(\n bd.getLocation().getWorld(),\n newPositionVector.x,\n newPositionVector.y,\n newPositionVector.z\n );\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.setTransformation(transformation);\n bd.teleport(newLocation);\n });\n\n }\n });\n\n\n\n }\n\n private Vector3f getRotatedPosition(Vector3f pointToRotate, Vector3f origin, Axis axis, float angle){\n pointToRotate.sub(origin);\n Matrix3f rotationMatrix = new Matrix3f();\n\n switch (axis){\n case X -> rotationMatrix.rotationX(angle);\n case Y -> rotationMatrix.rotationY(angle);\n case Z -> rotationMatrix.rotationZ(angle);\n }\n\n rotationMatrix.transform(pointToRotate);\n\n pointToRotate.add(origin);\n\n return pointToRotate;\n }\n\n public void move(Vector addition){\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n for(BlockDisplay bd : blockDisplays){\n bd.teleport(bd.getLocation().add(addition));\n }\n });\n }\n\n public void move(Axis axis, double addition){\n switch (axis){\n case X -> move(new Vector(addition, 0, 0));\n case Y -> move(new Vector(0, addition, 0));\n case Z -> move(new Vector(0, 0, addition));\n }\n }\n\n public double getBlockSize() {\n return blockSize;\n }\n\n public int getBlockCount(){\n return blockDisplays.size();\n }\n\n public List<BlockDisplay> getBlockDisplays(){\n return blockDisplays;\n }\n\n private Miniaturise getMain(){\n return (Miniaturise) Bukkit.getPluginManager().getPlugin(\"Miniaturise\");\n }\n\n}" }, { "identifier": "SelectedLocations", "path": "src/main/java/de/leghast/miniaturise/instance/region/SelectedLocations.java", "snippet": "public class SelectedLocations {\n\n private Location loc1;\n private Location loc2;\n\n public SelectedLocations(Location loc1, Location loc2){\n this.loc1 = loc1;\n this.loc2 = loc2;\n }\n\n public SelectedLocations(){\n this.loc1 = null;\n this.loc2 = null;\n }\n\n /**\n * @return The first location, that was selected\n * */\n public Location getLoc1(){\n return loc1;\n }\n\n /**\n * @return The second location, that was selected\n * */\n public Location getLoc2(){\n return loc2;\n }\n\n /**\n * Sets the first location\n *\n * @param loc1 The location to replace the old selected location\n * */\n public void setLoc1(Location loc1){\n this.loc1 = loc1;\n }\n\n /**\n * Sets the second location\n *\n * @param loc2 The location to replace the old selected location\n * */\n public void setLoc2(Location loc2){\n this.loc2 = loc2;\n }\n\n /**\n * @return If both locations are set\n */\n public boolean isValid(){\n return loc1 != null && loc2 != null;\n }\n\n}" }, { "identifier": "AdjusterSettings", "path": "src/main/java/de/leghast/miniaturise/instance/settings/AdjusterSettings.java", "snippet": "public class AdjusterSettings {\n\n private Player player;\n\n private PositionSettings positionSettings;\n private SizeSettings sizeSettings;\n private RotationSettings rotationSettings;\n\n private Page page;\n\n public AdjusterSettings(Player player){\n this.player = player;\n\n positionSettings = new PositionSettings(this);\n sizeSettings = new SizeSettings(this);\n rotationSettings = new RotationSettings(this);\n\n page = Page.POSITION;\n }\n\n public PositionSettings getPositionSettings(){\n return positionSettings;\n }\n\n public SizeSettings getSizeSettings(){\n return sizeSettings;\n }\n\n public RotationSettings getRotationSettings(){\n return rotationSettings;\n }\n\n public Page getPage(){\n return page;\n }\n\n public void setPage(Page page){\n this.page = page;\n }\n\n public Player getPlayer(){\n return player;\n }\n\n}" }, { "identifier": "ConfigManager", "path": "src/main/java/de/leghast/miniaturise/manager/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private static FileConfiguration config;\n\n //Setup/Initialise the ConfigManager\n public static void setupConfig(Miniaturise main){\n ConfigManager.config = main.getConfig();\n main.saveDefaultConfig();\n }\n\n /**\n * @return The selector tool material\n */\n public static Material getSelectorToolMaterial(){\n return Material.matchMaterial(config.getString(\"selector-tool\"));\n }\n\n /**\n * Set a new material as the selector tool\n *\n * @param material - The material, you want the selector tool to be\n */\n public static void setSelectorToolMaterial(Material material){\n config.set(\"selector-tool\", material.name());\n\n }\n\n /**\n * @return The maximum amount of blocks that are allowed in one miniature\n */\n public static int getMaxEntityLimit(){\n return config.getInt(\"max-entity-limit\");\n }\n\n /**\n * Set the maximum amount of blocks that are allowed in one miniature\n * NOTE: Higher numbers than the default value(1500) can lead to various performance issues. Handle with care and responsibility\n *\n * @param maxBlockLimit The new maximum amount of blocks that are allowed in one miniature\n */\n public static void setMaxEntityLimit(int maxBlockLimit){\n config.set(\"max-entity-limit\", maxBlockLimit);\n }\n\n /**\n * @return The default size of a block in a newly instanced miniature\n */\n public static double getDefaultSize(){\n return config.getDouble(\"default-size\");\n }\n\n /**\n * Set the default size of a block in a newly instanced miniature\n *\n * @param size The new default size of a block in a newly instanced miniature\n */\n public static void setDefaultSize(double size){\n config.set(\"default-size\", size);\n }\n\n public static Material getAdjusterToolMaterial(){\n return Material.matchMaterial(config.getString(\"adjuster-tool\"));\n }\n\n public static void setAdjusterToolMaterial(Material material){\n config.set(\"adjuster-tool\", material.name());\n }\n\n}" }, { "identifier": "UserInterface", "path": "src/main/java/de/leghast/miniaturise/ui/UserInterface.java", "snippet": "public class UserInterface {\n\n public UserInterface(Miniaturise main, Player player, Page page){\n Inventory inv = Bukkit.createInventory(null, 45, page.getTitle());\n switch (page){\n case POSITION -> {\n inv.setContents(PositionPage.getPositionPage(main, player));\n }\n case SIZE -> {\n inv.setContents(SizePage.getSizePage(main, player));\n }\n case ROTATION -> {\n inv.setContents(RotationPage.getRotationPage(main, player));\n }\n }\n player.openInventory(inv);\n }\n\n}" }, { "identifier": "Util", "path": "src/main/java/de/leghast/miniaturise/util/Util.java", "snippet": "public class Util {\n\n public static final String PREFIX = \"§7[§eMiniaturise§7] \";\n\n public static String getDimensionName(String string){\n switch (string){\n case \"NORMAL\" -> {\n return \"minecraft:overworld\";\n }\n case \"NETHER\" -> {\n return \"minecraft:the_nether\";\n }\n case \"THE_END\" -> {\n return \"minecraft:the_end\";\n }\n default -> {\n return \"Invalid dimension\";\n }\n }\n }\n\n public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){\n List<BlockDisplay> blockDisplays = new ArrayList<>();\n for(Chunk chunk : player.getWorld().getLoadedChunks()){\n for(Entity entity : chunk.getEntities()){\n if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){\n blockDisplays.add((BlockDisplay) entity);\n }\n }\n }\n return blockDisplays;\n }\n\n public static void setCustomNumberInput(Miniaturise main, Player player, Page page){\n ItemStack output = new ItemStack(Material.PAPER);\n ItemMeta meta = output.getItemMeta();\n meta.setDisplayName(\"§eSet custom factor\");\n output.setItemMeta(meta);\n PageUtil.addGlint(output);\n\n new AnvilGUI.Builder()\n .title(\"§eEnter custom factor\")\n .text(\"1\")\n .onClick((slot, stateSnapshot) -> {\n if(slot == AnvilGUI.Slot.OUTPUT){\n AdjusterSettings settings = main.getSettingsManager().getAdjusterSettings(player.getUniqueId());\n switch (page){\n case POSITION -> settings.getPositionSettings().setFactor(stateSnapshot.getText());\n case SIZE -> settings.getSizeSettings().setFactor(stateSnapshot.getText());\n case ROTATION -> settings.getRotationSettings().setFactor(stateSnapshot.getText());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.close());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.updateTitle(\"§eEnter custom factor\", false));\n })\n .preventClose()\n .itemOutput(output)\n .plugin(main)\n .open(player);\n\n }\n\n}" } ]
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.miniature.PlacedMiniature; import de.leghast.miniaturise.instance.region.SelectedLocations; import de.leghast.miniaturise.instance.settings.AdjusterSettings; import de.leghast.miniaturise.manager.ConfigManager; import de.leghast.miniaturise.ui.UserInterface; import de.leghast.miniaturise.util.Util; import org.bukkit.Material; import org.bukkit.block.Block; 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.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot;
4,555
package de.leghast.miniaturise.listener; /** * This class listens for player interactions, that are relevant for the Miniaturise plugin * @author GhastCraftHD * */ public class PlayerInteractListener implements Listener { private Miniaturise main; public PlayerInteractListener(Miniaturise main){ this.main = main; } @EventHandler public void onPlayerInteract(PlayerInteractEvent e){ Player player = e.getPlayer(); Material material = player.getInventory().getItemInMainHand().getType(); if(player.hasPermission("miniaturise.use")){ if(material == ConfigManager.getSelectorToolMaterial()){ e.setCancelled(true); handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand()); }else if(material == ConfigManager.getAdjusterToolMaterial()){ e.setCancelled(true); if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ handleAdjusterInteraction(player, e.getAction(), e.getHand()); }else{ player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature"); } } } } private void handleSelectorInteraction(Player player, Action action, Block block, EquipmentSlot hand){ switch (action){ case LEFT_CLICK_BLOCK -> { if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) { main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc1(block.getLocation()); } else { main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(block.getLocation(), null)); } player.sendMessage(Util.PREFIX + "§aThe first position was set to §e" + (int) block.getLocation().getX() + ", " + (int) block.getLocation().getY() + ", " + (int) block.getLocation().getZ() + " §a(" + Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")"); } case RIGHT_CLICK_BLOCK -> { if(hand == EquipmentSlot.HAND){ if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) { main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc2(block.getLocation()); } else { main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(null, block.getLocation())); } player.sendMessage(Util.PREFIX + "§aThe second position was set to §e" + (int) block.getLocation().getX() + ", " + (int) block.getLocation().getY() + ", " + (int) block.getLocation().getZ()+ " §a(" + Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")"); } } } } private void handleAdjusterInteraction(Player player, Action action, EquipmentSlot hand){ if(!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())){ main.getSettingsManager().addAdjusterSettings(player.getUniqueId()); } if(action.isLeftClick()){
package de.leghast.miniaturise.listener; /** * This class listens for player interactions, that are relevant for the Miniaturise plugin * @author GhastCraftHD * */ public class PlayerInteractListener implements Listener { private Miniaturise main; public PlayerInteractListener(Miniaturise main){ this.main = main; } @EventHandler public void onPlayerInteract(PlayerInteractEvent e){ Player player = e.getPlayer(); Material material = player.getInventory().getItemInMainHand().getType(); if(player.hasPermission("miniaturise.use")){ if(material == ConfigManager.getSelectorToolMaterial()){ e.setCancelled(true); handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand()); }else if(material == ConfigManager.getAdjusterToolMaterial()){ e.setCancelled(true); if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ handleAdjusterInteraction(player, e.getAction(), e.getHand()); }else{ player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature"); } } } } private void handleSelectorInteraction(Player player, Action action, Block block, EquipmentSlot hand){ switch (action){ case LEFT_CLICK_BLOCK -> { if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) { main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc1(block.getLocation()); } else { main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(block.getLocation(), null)); } player.sendMessage(Util.PREFIX + "§aThe first position was set to §e" + (int) block.getLocation().getX() + ", " + (int) block.getLocation().getY() + ", " + (int) block.getLocation().getZ() + " §a(" + Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")"); } case RIGHT_CLICK_BLOCK -> { if(hand == EquipmentSlot.HAND){ if (main.getRegionManager().hasSelectedLocations(player.getUniqueId())) { main.getRegionManager().getSelectedLocations(player.getUniqueId()).setLoc2(block.getLocation()); } else { main.getRegionManager().addSelectedLocations(player.getUniqueId(), new SelectedLocations(null, block.getLocation())); } player.sendMessage(Util.PREFIX + "§aThe second position was set to §e" + (int) block.getLocation().getX() + ", " + (int) block.getLocation().getY() + ", " + (int) block.getLocation().getZ()+ " §a(" + Util.getDimensionName(block.getLocation().getWorld().getEnvironment().name()) + ")"); } } } } private void handleAdjusterInteraction(Player player, Action action, EquipmentSlot hand){ if(!main.getSettingsManager().hasAdjusterSettings(player.getUniqueId())){ main.getSettingsManager().addAdjusterSettings(player.getUniqueId()); } if(action.isLeftClick()){
PlacedMiniature placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId());
1
2023-10-15 09:08:33+00:00
8k
zendo-games/zenlib
src/main/java/zendo/games/zenlib/screens/transitions/Transition.java
[ { "identifier": "ZenConfig", "path": "src/main/java/zendo/games/zenlib/ZenConfig.java", "snippet": "public class ZenConfig {\n\n public final Window window;\n public final UI ui;\n\n public ZenConfig() {\n this(\"zenlib\", 1280, 720, null);\n }\n\n public ZenConfig(String title, int width, int height) {\n this(title, width, height, null);\n }\n\n public ZenConfig(String title, int width, int height, String uiSkinPath) {\n this.window = new Window(title, width, height);\n this.ui = new UI(uiSkinPath);\n }\n\n public static class Window {\n public final String title;\n public final int width;\n public final int height;\n\n public Window(String title, int width, int height) {\n this.title = title;\n this.width = width;\n this.height = height;\n }\n }\n\n public static class UI {\n public final String skinPath;\n\n public UI() {\n this(null);\n }\n\n public UI(String skinPath) {\n this.skinPath = skinPath;\n }\n }\n}" }, { "identifier": "ZenMain", "path": "src/main/java/zendo/games/zenlib/ZenMain.java", "snippet": "public abstract class ZenMain<AssetsType extends ZenAssets> extends ApplicationAdapter {\n\n /**\n * Debug flags, toggle these values as needed, or override in project's ZenMain subclass\n */\n public static class Debug {\n public static boolean general = false;\n public static boolean shaders = false;\n public static boolean ui = false;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static ZenMain instance;\n\n public ZenConfig config;\n public AssetsType assets;\n public TweenManager tween;\n public FrameBuffer frameBuffer;\n public TextureRegion frameBufferRegion;\n public OrthographicCamera windowCamera;\n\n private Transition transition;\n\n public ZenMain(ZenConfig config) {\n ZenMain.instance = this;\n this.config = config;\n }\n\n /**\n * Override to create project-specific ZenAssets subclass instance\n */\n public abstract AssetsType createAssets();\n\n /**\n * Override to create project-specific ZenScreen subclass instance that will be used as the starting screen\n */\n public abstract ZenScreen createStartScreen();\n\n @Override\n public void create() {\n Time.init();\n\n // TODO - consider moving to ZenAssets\n tween = new TweenManager();\n Tween.setWaypointsLimit(4);\n Tween.setCombinedAttributesLimit(4);\n Tween.registerAccessor(Color.class, new ColorAccessor());\n Tween.registerAccessor(Rectangle.class, new RectangleAccessor());\n Tween.registerAccessor(Vector2.class, new Vector2Accessor());\n Tween.registerAccessor(Vector3.class, new Vector3Accessor());\n Tween.registerAccessor(OrthographicCamera.class, new CameraAccessor());\n\n frameBuffer = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, true);\n var texture = frameBuffer.getColorBufferTexture();\n texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n frameBufferRegion = new TextureRegion(texture);\n frameBufferRegion.flip(false, true);\n\n windowCamera = new OrthographicCamera();\n windowCamera.setToOrtho(false, config.window.width, config.window.height);\n windowCamera.update();\n\n assets = createAssets();\n\n transition = new Transition(config);\n setScreen(createStartScreen());\n }\n\n @Override\n public void dispose() {\n frameBuffer.dispose();\n transition.dispose();\n assets.dispose();\n }\n\n @Override\n public void resize(int width, int height) {\n var screen = currentScreen();\n if (screen != null) {\n screen.resize(width, height);\n }\n }\n\n public ZenScreen currentScreen() {\n return transition.screens.current;\n }\n\n public void update() {\n // handle global input\n // TODO - might not want to keep these in library code\n {\n if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {\n Gdx.app.exit();\n }\n if (Gdx.input.isKeyJustPressed(Input.Keys.F1)) {\n Debug.general = !Debug.general;\n Debug.ui = !Debug.ui;\n }\n }\n\n // update things that must update every tick\n {\n Time.update();\n tween.update(Time.delta);\n transition.alwaysUpdate(Time.delta);\n }\n\n // handle a pause\n if (Time.pause_timer > 0) {\n Time.pause_timer -= Time.delta;\n if (Time.pause_timer <= -0.0001f) {\n Time.delta = -Time.pause_timer;\n } else {\n // skip updates if we're paused\n return;\n }\n }\n Time.millis += (long) Time.delta;\n Time.previous_elapsed = Time.elapsed_millis();\n\n // update normally (if not paused)\n transition.update(Time.delta);\n }\n\n @Override\n public void render() {\n update();\n var batch = assets.batch;\n var screens = transition.screens;\n\n screens.current.renderFrameBuffers(batch);\n if (screens.next == null) {\n screens.current.render(batch);\n } else {\n transition.render(batch, windowCamera);\n }\n }\n\n public void setScreen(ZenScreen currentScreen) {\n setScreen(currentScreen, null, Transition.DEFAULT_SPEED);\n }\n\n public void setScreen(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {\n // only one transition at a time\n if (transition.active) return;\n if (transition.screens.next != null) return;\n\n var screens = transition.screens;\n if (screens.current == null) {\n // no current screen set, go ahead and set it\n screens.current = newScreen;\n } else {\n // current screen is set, so trigger transition to new screen\n transition.startTransition(newScreen, type, transitionSpeed);\n }\n }\n}" }, { "identifier": "ZenTransition", "path": "src/main/java/zendo/games/zenlib/assets/ZenTransition.java", "snippet": "public enum ZenTransition {\n // spotless:off\n blinds\n , circle_crop\n , crosshatch\n , cube\n , dissolve\n , doom_drip\n , dreamy\n , heart\n , pixelize\n , radial\n , ripple\n , simple_zoom\n , stereo\n ;\n // spotless:on\n\n public ShaderProgram shader;\n public static boolean initialized = false;\n\n ZenTransition() {\n this.shader = null;\n }\n\n public static void init() {\n var vertSrcPath = \"shaders/transitions/default.vert\";\n for (var value : values()) {\n var fragSrcPath = \"shaders/transitions/\" + value.name() + \".frag\";\n value.shader = loadShader(vertSrcPath, fragSrcPath);\n }\n initialized = true;\n }\n\n public static ShaderProgram random() {\n if (!initialized) {\n throw new GdxRuntimeException(\n \"Failed to get random screen transition shader, ScreenTransitions is not initialized\");\n }\n\n var random = (int) (Math.random() * values().length);\n return values()[random].shader;\n }\n\n public static ShaderProgram loadShader(String vertSourcePath, String fragSourcePath) {\n ShaderProgram.pedantic = false;\n var shaderProgram = new ShaderProgram(\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + vertSourcePath),\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + fragSourcePath));\n var log = shaderProgram.getLog();\n\n if (!shaderProgram.isCompiled()) {\n throw new GdxRuntimeException(\"LoadShader: compilation failed for \" + \"'\" + vertSourcePath + \"' and '\"\n + fragSourcePath + \"':\\n\" + log);\n } else if (ZenMain.Debug.shaders) {\n Gdx.app.debug(\"LoadShader\", \"ShaderProgram compilation log: \" + log);\n }\n\n return shaderProgram;\n }\n}" }, { "identifier": "ZenScreen", "path": "src/main/java/zendo/games/zenlib/screens/ZenScreen.java", "snippet": "public abstract class ZenScreen implements Disposable {\n\n public final SpriteBatch batch;\n public final TweenManager tween;\n public final OrthographicCamera windowCamera;\n public final Vector3 pointerPos;\n\n protected OrthographicCamera worldCamera;\n protected Viewport viewport;\n protected Stage uiStage;\n protected Skin skin;\n protected boolean exitingScreen;\n\n public ZenScreen() {\n var main = ZenMain.instance;\n\n this.batch = main.assets.batch;\n this.tween = main.tween;\n this.windowCamera = main.windowCamera;\n this.pointerPos = new Vector3();\n this.worldCamera = new OrthographicCamera();\n this.viewport = new ScreenViewport(worldCamera);\n this.viewport.update(main.config.window.width, main.config.window.height, true);\n this.exitingScreen = false;\n\n initializeUI();\n }\n\n @Override\n public void dispose() {}\n\n public void resize(int width, int height) {\n viewport.update(width, height, true);\n }\n\n /**\n * Update something in the screen even when\n * {@code Time.pause_for()} is being processed\n * @param dt the time in seconds since the last frame\n */\n public void alwaysUpdate(float dt) {}\n\n public void update(float dt) {\n windowCamera.update();\n worldCamera.update();\n uiStage.act(dt);\n }\n\n public void renderFrameBuffers(SpriteBatch batch) {}\n\n public abstract void render(SpriteBatch batch);\n\n protected void initializeUI() {\n skin = VisUI.getSkin();\n\n var viewport = new ScreenViewport(windowCamera);\n uiStage = new Stage(viewport, batch);\n\n // extend and setup any per-screen ui widgets in here...\n }\n}" }, { "identifier": "Time", "path": "src/main/java/zendo/games/zenlib/utils/Time.java", "snippet": "public class Time {\n\n private static class CallbackInfo {\n private final Callback callback;\n private final Object[] params;\n private float timer;\n\n public float timeout = 0;\n public float interval = 0;\n\n CallbackInfo(Callback callback, Object... params) {\n this.callback = callback;\n this.params = params;\n this.timer = 0;\n }\n\n boolean isInterval() {\n return (interval > 0);\n }\n\n boolean isTimeout() {\n return (timeout > 0);\n }\n\n boolean update(float dt) {\n boolean called = false;\n\n timer += dt;\n\n if (interval > 0) {\n if (timer >= interval) {\n timer -= interval;\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n } else {\n if (timer >= timeout) {\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n }\n\n return called;\n }\n }\n\n private static long start_millis = 0;\n\n public static long millis = 0;\n public static long previous_elapsed = 0;\n public static float delta = 0;\n public static float pause_timer = 0;\n\n private static Array<CallbackInfo> callbacks;\n\n public static void init() {\n start_millis = TimeUtils.millis();\n callbacks = new Array<>();\n }\n\n public static void update() {\n Time.delta = Calc.min(1 / 30f, Gdx.graphics.getDeltaTime());\n\n for (int i = callbacks.size - 1; i >= 0; i--) {\n CallbackInfo info = callbacks.get(i);\n boolean wasCalled = info.update(Time.delta);\n if (wasCalled && info.isTimeout()) {\n callbacks.removeIndex(i);\n }\n }\n }\n\n public static void do_after_delay(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.timeout = seconds;\n callbacks.add(info);\n }\n\n public static void do_at_interval(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.interval = seconds;\n callbacks.add(info);\n }\n\n public static long elapsed_millis() {\n return TimeUtils.timeSinceMillis(start_millis);\n }\n\n public static void pause_for(float time) {\n if (time >= pause_timer) {\n pause_timer = time;\n }\n }\n\n public static boolean on_time(float time, float timestamp) {\n return (time >= timestamp) && ((time - Time.delta) < timestamp);\n }\n\n public static boolean on_interval(float time, float delta, float interval, float offset) {\n return Calc.floor((time - offset - delta) / interval) < Calc.floor((time - offset) / interval);\n }\n\n public static boolean on_interval(float delta, float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), delta, interval, offset);\n }\n\n public static boolean on_interval(float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), Time.delta, interval, offset);\n }\n\n public static boolean on_interval(float interval) {\n return Time.on_interval(interval, 0);\n }\n\n public static boolean between_interval(float time, float interval, float offset) {\n return Calc.modf(time - offset, interval * 2) >= interval;\n }\n\n public static boolean between_interval(float interval, float offset) {\n return Time.between_interval(Time.elapsed_millis(), interval, offset);\n }\n\n public static boolean between_interval(float interval) {\n return Time.between_interval(interval, 0);\n }\n}" } ]
import aurelienribon.tweenengine.Timeline; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.primitives.MutableFloat; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Disposable; import zendo.games.zenlib.ZenConfig; import zendo.games.zenlib.ZenMain; import zendo.games.zenlib.assets.ZenTransition; import zendo.games.zenlib.screens.ZenScreen; import zendo.games.zenlib.utils.Time;
4,075
package zendo.games.zenlib.screens.transitions; public class Transition implements Disposable { public static final float DEFAULT_SPEED = 0.66f; public boolean active; public MutableFloat percent; public ShaderProgram shader; public final Screens screens = new Screens(); public final FrameBuffers fbo = new FrameBuffers(); public final Textures tex = new Textures(); private final ZenConfig config; public Transition(ZenConfig config) { this.config = config; this.active = false; this.percent = new MutableFloat(0); this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.tex.from = this.fbo.from.getColorBufferTexture(); this.tex.to = this.fbo.to.getColorBufferTexture(); } @Override public void dispose() { screens.dispose(); fbo.dispose(); // no need to dispose textures here, // they are owned by the frame buffers } public void alwaysUpdate(float dt) { screens.current.alwaysUpdate(dt); if (screens.next != null) { screens.next.alwaysUpdate(dt); } } public void update(float dt) { screens.current.update(dt); if (screens.next != null) { screens.next.update(dt); } } public void render(SpriteBatch batch, OrthographicCamera windowCamera) { screens.next.update(Time.delta); screens.next.renderFrameBuffers(batch); // draw the next screen to the 'to' buffer fbo.to.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.next.render(batch); } fbo.to.end(); // draw the current screen to the 'from' buffer fbo.from.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.current.render(batch); } fbo.from.end(); // draw the transition buffer to the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setShader(shader); batch.setProjectionMatrix(windowCamera.combined); batch.begin(); { tex.from.bind(1); shader.setUniformi("u_texture1", 1); tex.to.bind(0); shader.setUniformi("u_texture", 0); shader.setUniformf("u_percent", percent.floatValue()); batch.setColor(Color.WHITE); batch.draw(tex.to, 0, 0, config.window.width, config.window.height); } batch.end(); batch.setShader(null); }
package zendo.games.zenlib.screens.transitions; public class Transition implements Disposable { public static final float DEFAULT_SPEED = 0.66f; public boolean active; public MutableFloat percent; public ShaderProgram shader; public final Screens screens = new Screens(); public final FrameBuffers fbo = new FrameBuffers(); public final Textures tex = new Textures(); private final ZenConfig config; public Transition(ZenConfig config) { this.config = config; this.active = false; this.percent = new MutableFloat(0); this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.tex.from = this.fbo.from.getColorBufferTexture(); this.tex.to = this.fbo.to.getColorBufferTexture(); } @Override public void dispose() { screens.dispose(); fbo.dispose(); // no need to dispose textures here, // they are owned by the frame buffers } public void alwaysUpdate(float dt) { screens.current.alwaysUpdate(dt); if (screens.next != null) { screens.next.alwaysUpdate(dt); } } public void update(float dt) { screens.current.update(dt); if (screens.next != null) { screens.next.update(dt); } } public void render(SpriteBatch batch, OrthographicCamera windowCamera) { screens.next.update(Time.delta); screens.next.renderFrameBuffers(batch); // draw the next screen to the 'to' buffer fbo.to.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.next.render(batch); } fbo.to.end(); // draw the current screen to the 'from' buffer fbo.from.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.current.render(batch); } fbo.from.end(); // draw the transition buffer to the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setShader(shader); batch.setProjectionMatrix(windowCamera.combined); batch.begin(); { tex.from.bind(1); shader.setUniformi("u_texture1", 1); tex.to.bind(0); shader.setUniformi("u_texture", 0); shader.setUniformf("u_percent", percent.floatValue()); batch.setColor(Color.WHITE); batch.draw(tex.to, 0, 0, config.window.width, config.window.height); } batch.end(); batch.setShader(null); }
public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {
3
2023-10-21 19:36:50+00:00
8k
tuna-pizza/GraphXings
src/GraphXings/Legacy/Game/Game.java
[ { "identifier": "CrossingCalculator", "path": "src/GraphXings/Algorithms/CrossingCalculator.java", "snippet": "public class CrossingCalculator\r\n{\r\n /**\r\n * The graph g.\r\n */\r\n private Graph g;\r\n /**\r\n * The positions of the already placed vertices.\r\n */\r\n private HashMap<Vertex, Coordinate> vertexCoordinates;\r\n\r\n /**\r\n * Constructs a CrossingCalculator object.\r\n * @param g The partially embedded graph.\r\n * @param vertexCoordinates The coordinates of the already placed vertices.\r\n */\r\n public CrossingCalculator(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates)\r\n {\r\n this.g = g;\r\n this.vertexCoordinates = vertexCoordinates;\r\n }\r\n\r\n /**\r\n * Computes the number of crossings. The implementation is not efficient and iterates over all pairs of edges resulting in quadratic time.\r\n * @return The number of crossings.\r\n */\r\n public int computeCrossingNumber()\r\n {\r\n int crossingNumber = 0;\r\n for (Edge e1 : g.getEdges())\r\n {\r\n for (Edge e2 : g.getEdges())\r\n {\r\n if (!e1.equals(e2))\r\n {\r\n if (!e1.isAdjacent(e2))\r\n {\r\n if (!vertexCoordinates.containsKey(e1.getS()) || !vertexCoordinates.containsKey(e1.getT()) || !vertexCoordinates.containsKey(e2.getS())|| !vertexCoordinates.containsKey(e2.getT()))\r\n {\r\n continue;\r\n }\r\n Segment s1 = new Segment(vertexCoordinates.get(e1.getS()),vertexCoordinates.get(e1.getT()));\r\n Segment s2 = new Segment(vertexCoordinates.get(e2.getS()),vertexCoordinates.get(e2.getT()));\r\n if (Segment.intersect(s1,s2))\r\n {\r\n crossingNumber++;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return crossingNumber/2;\r\n }\r\n\r\n /**\r\n * Computes the sum of the squared cosines of crossing angles. The implementation is not efficient and iterates over all pairs of edges resulting in quadratic time.\r\n * @return The sum of the squared cosines of crossing angles.\r\n */\r\n public double computeSumOfSquaredCosinesOfCrossingAngles()\r\n {\r\n int comp = 0;\r\n double result = 0;\r\n for (Edge e1 : g.getEdges())\r\n {\r\n for (Edge e2 : g.getEdges())\r\n {\r\n if (!e1.equals(e2))\r\n {\r\n if (!e1.isAdjacent(e2))\r\n {\r\n if (!vertexCoordinates.containsKey(e1.getS()) || !vertexCoordinates.containsKey(e1.getT()) || !vertexCoordinates.containsKey(e2.getS())|| !vertexCoordinates.containsKey(e2.getT()))\r\n {\r\n continue;\r\n }\r\n Segment s1 = new Segment(vertexCoordinates.get(e1.getS()),vertexCoordinates.get(e1.getT()));\r\n Segment s2 = new Segment(vertexCoordinates.get(e2.getS()),vertexCoordinates.get(e2.getT()));\r\n if (Segment.intersect(s1,s2))\r\n {\r\n result+=Segment.squaredCosineOfAngle(s1,s2);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result/2;\r\n }\r\n}\r" }, { "identifier": "GameMove", "path": "src/GraphXings/Game/GameMove.java", "snippet": "public class GameMove\r\n{\r\n /**\r\n * The vertex to be placed.\r\n */\r\n private Vertex v;\r\n /**\r\n * The coordinate to place the vertex to.\r\n */\r\n private Coordinate c;\r\n /**\r\n * Constructs a GameMove object.\r\n * @param v The vertex to be placed at c.\r\n * @param c The coordinate where v is to be placed.\r\n */\r\n public GameMove(Vertex v, Coordinate c)\r\n {\r\n this.v = v;\r\n this.c = c;\r\n }\r\n\r\n /**\r\n * Returns the vertex to be placed.\r\n * @return The vertex to be placed.\r\n */\r\n public Vertex getVertex()\r\n {\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the coordinate to be used.\r\n * @return The coordinate to be used.\r\n */\r\n public Coordinate getCoordinate()\r\n {\r\n return c;\r\n }\r\n}\r" }, { "identifier": "GameState", "path": "src/GraphXings/Game/GameState.java", "snippet": "public class GameState\n{\n\t/**\n\t * The set of vertices contained in the graph.\n\t */\n\tprivate HashSet<Vertex> vertices;\n\t/**\n\t * A HashMap mapping vertices to their coordinates if already placed.\n\t */\n\tprivate HashMap<Vertex, Coordinate> vertexCoordinates;\n\t/**\n\t * A collection of vertices that have already been placed.\n\t */\n\tprivate HashSet<Vertex> placedVertices;\n\t/**\n\t * The width of the drawing.\n\t */\n\tprivate int width;\n\t/**\n\t * The height of the drawing.\n\t */\n\tprivate int height;\n\t/**\n\t * A 0-1 map describing which coordinates have already been used.\n\t */\n\tprivate int[][] usedCoordinates;\n\n\t/**\n\t * Creates a new GameState object describing the initial empty game board.\n\t * @param g The graph to be drawn.\n\t * @param width The width of the game board.\n\t * @param height The height of the game board.\n\t */\n\tpublic GameState(Graph g, int width, int height)\n\t{\n\t\tvertices = new HashSet<>();\n\t\tfor (Vertex v : g.getVertices())\n\t\t{\n\t\t\tvertices.add(v);\n\t\t}\n\t\tvertexCoordinates = new HashMap<>();\n\t\tplacedVertices = new HashSet<>();\n\t\tusedCoordinates = new int[width][height];\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tfor (int y=0; y < height; y++)\n\t\t\t{\n\t\t\t\tusedCoordinates[x][y] = 0;\n\t\t\t}\n\t\t}\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\n\t/**\n\t * Checks if a move is valid given the current state of the game.\n\t * @param newMove The potential move to be performed.\n\t * @return True if the move is valid, false if it is invalid.\n\t */\n\tpublic boolean checkMoveValidity(GameMove newMove)\n\t{\n\t\tif (newMove.getVertex() == null ||newMove.getCoordinate() == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (!vertices.contains(newMove.getVertex()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (placedVertices.contains(newMove.getVertex()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tint x = newMove.getCoordinate().getX();\n\t\tint y = newMove.getCoordinate().getY();\n\t\tif (x >= width || y >= height)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (usedCoordinates[x][y] != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies changes to the game state according to the new move.\n\t * @param newMove The new move to be performed.\n\t */\n\tpublic void applyMove(GameMove newMove)\n\t{\n\t\tusedCoordinates[newMove.getCoordinate().getX()][newMove.getCoordinate().getY()]=1;\n placedVertices.add(newMove.getVertex());\n vertexCoordinates.put(newMove.getVertex(), newMove.getCoordinate());\n\t}\n\n\t/**\n\t * Gets the set of placed vertices.\n\t * @return The set of placed vertices.\n\t */\n\tpublic HashSet<Vertex> getPlacedVertices()\n\t{\n\t\treturn placedVertices;\n\t}\n\n\t/**\n\t * Gets the coordinates assigned to vertices.\n\t * @return A HashMap describing the coordinate of vertices.\n\t */\n\tpublic HashMap<Vertex, Coordinate> getVertexCoordinates()\n\t{\n\t\treturn vertexCoordinates;\n\t}\n\n\t/**\n\t * Gets a 0-1 map of the already used vertices.\n\t * @return\n\t */\n\tpublic int[][] getUsedCoordinates()\n\t{\n\t\treturn usedCoordinates;\n\t}\n}" }, { "identifier": "Player", "path": "src/GraphXings/Legacy/Algorithms/Player.java", "snippet": "public interface Player\n{\n /**\n * Tells the player to perform the next move where the objective is to create crossings! In a valid move, a vertex of g that is not belonging to placedVertices is positioned onto a coordinate that is\n * not marked with a 1 in usedCoordinates. In addition, only the x-coordinates 0 to width-1 and the y-coordinates 0 to height-1 are allowed.\n * @param g The graph to be drawn.\n * @param vertexCoordinates The coordinates of the already placed vertices. Implemented as a HashMap mapping the Vertex object to its Coordinate.\n * @param gameMoves A sorted list of the already performed game moves.\n * @param usedCoordinates A 0-1 map of the coordinates of the allowed grid. Coordinates that have been used contain a 1 in the map, otherwise 0.\n * @param placedVertices A set of the already placed vertices.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @return The move to be performed.\n */\n public GameMove maximizeCrossings(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates, List<GameMove> gameMoves, int[][] usedCoordinates, HashSet<Vertex> placedVertices, int width, int height);\n /**\n * Tells the player to perform the next move where the objective is to avoid crossings! In a valid move, a vertex of g that is not belonging to placedVertices is positioned onto a coordinate that is\n * not marked with a 1 in usedCoordinates. In addition, only the x-coordinates 0 to width-1 and the y-coordinates 0 to height-1 are allowed.\n * @param g The graph to be drawn.\n * @param vertexCoordinates The coordinates of the already placed vertices. Implemented as a HashMap mapping the Vertex object to its Coordinate.\n * @param gameMoves A sorted list of the already performed game moves.\n * @param usedCoordinates A 0-1 map of the coordinates of the allowed grid. Coordinates that have been used contain a 1 in the map, otherwise 0.\n * @param placedVertices A set of the already placed vertices.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @return The move to be performed.\n */\n public GameMove minimizeCrossings(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates, List<GameMove> gameMoves, int[][] usedCoordinates, HashSet<Vertex> placedVertices, int width, int height);\n\n /**\n * Tells the player to get ready for the next round.\n * @param g The graph to be drawn in the next round.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @param role The role in the next round, either MAX or MIN.\n */\n public void initializeNextRound(Graph g, int width, int height, Role role);\n /**\n * Gets the name of the player.\n * @return The player's name.\n */\n public String getName();\n\n /**\n * An enum describing the role of the player in the next round.\n */\n public enum Role {MAX,MIN};\n}" }, { "identifier": "Graph", "path": "src/GraphXings/Data/Graph.java", "snippet": "public class Graph\r\n{\r\n /**\r\n * The vertex set.\r\n */\r\n private HashSet<Vertex> vertices;\r\n /**\r\n * The edge set.\r\n */\r\n private HashSet<Edge> edges;\r\n /**\r\n * The adjacency list representation.\r\n */\r\n private HashMap<Vertex,HashSet<Edge>> adjacentEdges;\r\n /**\r\n * The number of vertices.\r\n */\r\n private int n;\r\n /**\r\n * The number of edges.\r\n */\r\n private int m;\r\n\r\n /**\r\n * Initializes an empty graph.\r\n */\r\n public Graph()\r\n {\r\n vertices = new HashSet<>();\r\n edges = new HashSet<>();\r\n adjacentEdges = new HashMap<>();\r\n n = 0;\r\n m = 0;\r\n }\r\n\r\n /**\r\n * Adds a vertex to the graph.\r\n * @param v The vertex to be added.\r\n */\r\n public void addVertex(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n vertices.add(v);\r\n adjacentEdges.put(v,new HashSet<>());\r\n n++;\r\n }\r\n }\r\n\r\n /**\r\n * Add an edge to the graph.\r\n * @param e The edge to be added.\r\n * @return True, if the edge was successfully added, false otherwise.\r\n */\r\n public boolean addEdge(Edge e)\r\n {\r\n if (vertices.contains(e.getS())&&vertices.contains(e.getT()))\r\n {\r\n if (!adjacentEdges.get(e.getS()).contains(e))\r\n {\r\n adjacentEdges.get(e.getS()).add(e);\r\n adjacentEdges.get(e.getT()).add(e);\r\n edges.add(e);\r\n m++;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Gets the vertex set.\r\n * @return An Iterable over the vertex set.\r\n */\r\n public Iterable<Vertex> getVertices()\r\n {\r\n return vertices;\r\n }\r\n\r\n /**\r\n * Returns the edges incident to a specified vertex.\r\n * @param v The vertex whose adjacent edges are queried.\r\n * @return An Iterable over the edges incident to Vertex v.\r\n */\r\n public Iterable<Edge> getIncidentEdges(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n return null;\r\n }\r\n return adjacentEdges.get(v);\r\n }\r\n\r\n /**\r\n * Returns the edges of the graph.\r\n * @return An Iterable over the edge set.\r\n */\r\n public Iterable<Edge> getEdges()\r\n {\r\n return edges;\r\n }\r\n\r\n /**\r\n * Get the number of vertices.\r\n * @return The number of vertices.\r\n */\r\n public int getN()\r\n {\r\n return n;\r\n }\r\n\r\n /**\r\n * Gets the number of edges.\r\n * @return The number of edges.\r\n */\r\n public int getM()\r\n {\r\n return m;\r\n }\r\n\r\n /**\r\n * Creates a functionally equivalent copy of the graph that uses different references.\r\n * @return A Graph object containing a copy of the graph.\r\n */\r\n public Graph copy()\r\n {\r\n Graph copy = new Graph();\r\n for (Vertex v : vertices)\r\n {\r\n copy.addVertex(v);\r\n }\r\n for (Edge e : edges)\r\n {\r\n copy.addEdge(e);\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * Shuffles the order of vertices in the vertex set.\r\n */\r\n public void shuffleIndices()\r\n {\r\n List<Vertex> toBeShuffled = new ArrayList<>(vertices);\r\n Collections.shuffle(toBeShuffled);\r\n vertices = new HashSet<>(toBeShuffled);\r\n }\r\n\r\n /**\r\n * Provides the adjacency list representation of the graph.\r\n * @return The adjacency list representation.\r\n */\r\n @Override\r\n public String toString()\r\n {\r\n String out = \"\";\r\n for (Vertex v : vertices)\r\n {\r\n out += v.getId() + \": [\";\r\n for (Edge e: adjacentEdges.get(v))\r\n {\r\n out += \"(\" + e.getS().getId() +\",\" + e.getT().getId() +\"),\";\r\n }\r\n out += \"]\\n\";\r\n }\r\n return out;\r\n }\r\n}\r" } ]
import GraphXings.Algorithms.CrossingCalculator; import GraphXings.Game.GameMove; import GraphXings.Game.GameState; import GraphXings.Legacy.Algorithms.Player; import GraphXings.Data.Graph; import java.util.*;
4,772
package GraphXings.Legacy.Game; /** * A class for managing a game of GraphXings! */ public class Game { /** * Decides whether or not data is copied before being passed on to players. */ public static boolean safeMode = true; /** * The width of the game board. */ private int width; /** * The height of the game board. */ private int height; /** * The graph to be drawn. */ private Graph g; /** * The first player. */ private Player player1; /** * The second player. */ private Player player2; /** * The time limit for players. */ private long timeLimit; /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. */ public Game(Graph g, int width, int height, Player player1, Player player2) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = Long.MAX_VALUE; } /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. * @param timeLimit The time limit for players. */ public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = timeLimit; } /** * Runs the full game of GraphXings. * @return Provides a GameResult Object containing the game's results. */ public GameResult play() { Random r = new Random(System.nanoTime()); if (r.nextBoolean()) { Player swap = player1; player1 = player2; player2 = swap; } try { player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX); player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN); int crossingsGame1 = playRound(player1, player2); player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN); player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX); int crossingsGame2 = playRound(player2, player1); return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false); } catch (InvalidMoveException ex) { System.err.println(ex.getCheater().getName() + " cheated!"); if (ex.getCheater().equals(player1)) { return new GameResult(0, 0, player1, player2,true,false,false,false); } else if (ex.getCheater().equals(player2)) { return new GameResult(0,0,player1,player2,false,true,false,false); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } catch (TimeOutException ex) { System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!"); if (ex.getTimeOutPlayer().equals(player1)) { return new GameResult(0, 0, player1, player2,false,false,true,false); } else if (ex.getTimeOutPlayer().equals(player2)) { return new GameResult(0,0,player1,player2,false,false,false,true); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } } /** * Plays a single round of the game. * @param maximizer The player with the goal to maximize the number of crossings. * @param minimizer The player with the goal to minimize the number of crossings * @return The number of crossings yielded in the final drawing. * @throws InvalidMoveException An exception caused by cheating. */ private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException { int turn = 0; GameState gs = new GameState(g,width,height);
package GraphXings.Legacy.Game; /** * A class for managing a game of GraphXings! */ public class Game { /** * Decides whether or not data is copied before being passed on to players. */ public static boolean safeMode = true; /** * The width of the game board. */ private int width; /** * The height of the game board. */ private int height; /** * The graph to be drawn. */ private Graph g; /** * The first player. */ private Player player1; /** * The second player. */ private Player player2; /** * The time limit for players. */ private long timeLimit; /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. */ public Game(Graph g, int width, int height, Player player1, Player player2) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = Long.MAX_VALUE; } /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. * @param timeLimit The time limit for players. */ public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = timeLimit; } /** * Runs the full game of GraphXings. * @return Provides a GameResult Object containing the game's results. */ public GameResult play() { Random r = new Random(System.nanoTime()); if (r.nextBoolean()) { Player swap = player1; player1 = player2; player2 = swap; } try { player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX); player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN); int crossingsGame1 = playRound(player1, player2); player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN); player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX); int crossingsGame2 = playRound(player2, player1); return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false); } catch (InvalidMoveException ex) { System.err.println(ex.getCheater().getName() + " cheated!"); if (ex.getCheater().equals(player1)) { return new GameResult(0, 0, player1, player2,true,false,false,false); } else if (ex.getCheater().equals(player2)) { return new GameResult(0,0,player1,player2,false,true,false,false); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } catch (TimeOutException ex) { System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!"); if (ex.getTimeOutPlayer().equals(player1)) { return new GameResult(0, 0, player1, player2,false,false,true,false); } else if (ex.getTimeOutPlayer().equals(player2)) { return new GameResult(0,0,player1,player2,false,false,false,true); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } } /** * Plays a single round of the game. * @param maximizer The player with the goal to maximize the number of crossings. * @param minimizer The player with the goal to minimize the number of crossings * @return The number of crossings yielded in the final drawing. * @throws InvalidMoveException An exception caused by cheating. */ private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException { int turn = 0; GameState gs = new GameState(g,width,height);
LinkedList<GameMove> gameMoves = new LinkedList<>();
1
2023-10-18 12:11:38+00:00
8k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/ThingAccessUtils.java
[ { "identifier": "AccessCheckInput", "path": "src/com/identityworksllc/iiq/common/access/AccessCheckInput.java", "snippet": "public final class AccessCheckInput {\n /**\n * Configuration\n */\n private CommonSecurityConfig configuration;\n\n /**\n * The plugin resource\n */\n private BasePluginResource pluginResource;\n\n /**\n * The state from this access check\n */\n private Map<String, Object> state;\n\n /**\n * The target Identity being checked (may be null)\n */\n private Identity target;\n\n /**\n * The name of the thing being checked\n */\n private String thingName;\n\n /**\n * Constructs a basic access check input\n */\n public AccessCheckInput() {\n\n }\n\n /**\n * Copy constructor allowing override of an input\n *\n * @param parent The parent config\n * @param config The 'child' config to replace with\n */\n public AccessCheckInput(AccessCheckInput parent, CommonSecurityConfig config) {\n this.state = parent.state;\n this.pluginResource = parent.pluginResource;\n this.thingName = parent.thingName;\n this.target = parent.target;\n this.configuration = config;\n }\n\n /**\n * Access check input taking a plugin or target\n *\n * @param pluginResource The plugin resource\n * @param target The target\n * @param config The config\n */\n public AccessCheckInput(BasePluginResource pluginResource, Identity target, CommonSecurityConfig config) {\n this.pluginResource = pluginResource;\n this.target = target;\n this.configuration = config;\n }\n\n /**\n * Access check input taking a plugin or target\n *\n * @param pluginResource The plugin resource\n * @param target The target\n * @param thingName The thing name\n * @param config The config\n */\n public AccessCheckInput(BasePluginResource pluginResource, Identity target, String thingName, CommonSecurityConfig config) {\n this.pluginResource = pluginResource;\n this.target = target;\n this.configuration = config;\n this.thingName = thingName;\n }\n\n public CommonSecurityConfig getConfiguration() {\n return configuration;\n }\n\n public BasePluginResource getPluginResource() {\n return pluginResource;\n }\n\n public Map<String, Object> getState() {\n return state;\n }\n\n public Identity getTarget() {\n return target;\n }\n\n public String getThingName() {\n return thingName;\n }\n\n public void setConfiguration(CommonSecurityConfig configuration) {\n this.configuration = configuration;\n }\n\n public void setPluginResource(BasePluginResource pluginResource) {\n this.pluginResource = pluginResource;\n }\n\n public void setState(Map<String, Object> state) {\n this.state = state;\n }\n\n public void setTarget(Identity target) {\n this.target = target;\n }\n\n public void setThingName(String thingName) {\n this.thingName = thingName;\n }\n}" }, { "identifier": "AccessCheckResponse", "path": "src/com/identityworksllc/iiq/common/access/AccessCheckResponse.java", "snippet": "@JsonAutoDetect\npublic class AccessCheckResponse implements Mappable {\n private static final Log log = LogFactory.getLog(AccessCheckResponse.class);\n\n /**\n * Whether the access was allowed\n */\n @JsonSerialize(using = StdJdkSerializers.AtomicBooleanSerializer.class)\n private final AtomicBoolean allowed;\n\n /**\n * Any output messages from the access check\n */\n private final List<StampedMessage> messages;\n\n /**\n * The timestamp of the check\n */\n private final long timestamp;\n\n /**\n * Basic constructor used by actual users of this class\n */\n public AccessCheckResponse() {\n this.timestamp = System.currentTimeMillis();\n this.allowed = new AtomicBoolean(true);\n this.messages = new ArrayList<>();\n }\n\n /**\n * Jackson-specific constructor. Don't use this one unless you're a JSON library.\n *\n * @param allowed The value of the allowed flag\n * @param messages The messages (possibly null) to add to a new empty list\n * @param timestamp The timestamp from the JSON\n */\n @JsonCreator\n public AccessCheckResponse(@JsonProperty(\"allowed\") boolean allowed, @JsonProperty(\"messages\") List<StampedMessage> messages, @JsonProperty(value = \"timestamp\", defaultValue = \"0\") long timestamp) {\n this.allowed = new AtomicBoolean(allowed);\n this.messages = new ArrayList<>();\n\n if (messages != null) {\n this.messages.addAll(messages);\n }\n\n if (timestamp == 0) {\n this.timestamp = System.currentTimeMillis();\n } else {\n this.timestamp = timestamp;\n }\n }\n\n /**\n * Adds a message to the collection\n * @param message The message to add\n */\n public void addMessage(String message) {\n this.messages.add(new StampedMessage(message));\n }\n\n /**\n * Adds a message to the collection\n * @param message The message to add\n */\n public void addMessage(Message message) {\n this.messages.add(new StampedMessage(message));\n }\n\n /**\n * Denies access to the thing, setting the allowed flag to false\n */\n public void deny() {\n this.allowed.set(false);\n }\n\n /**\n * Denies access to the thing, additionally logging a message indicating the denial reason\n * @param reason the denial reason\n */\n public void denyMessage(String reason) {\n this.messages.add(new StampedMessage(LogLevel.WARN, reason));\n deny();\n if (log.isDebugEnabled()) {\n log.debug(reason);\n }\n }\n\n /**\n * Gets the stored messages\n * @return The stored messages\n */\n public List<StampedMessage> getMessages() {\n return messages;\n }\n\n /**\n * Gets the timestamp\n * @return The timestamp\n */\n public long getTimestamp() {\n return timestamp;\n }\n\n /**\n * Returns true if the access was allowed\n * @return True if access was allowed\n */\n public boolean isAllowed() {\n return this.allowed.get();\n }\n\n /**\n * Merges this response with another response. If either response indicates that\n * access is not allowed, then it will be set to false in this object. Also, messages\n * will be merged.\n *\n * @param other The other object to merge\n */\n public void merge(AccessCheckResponse other) {\n if (!other.allowed.get()) {\n deny();\n }\n\n messages.addAll(other.messages);\n }\n}" }, { "identifier": "DummyPluginResource", "path": "src/com/identityworksllc/iiq/common/auth/DummyPluginResource.java", "snippet": "public class DummyPluginResource extends BasePluginResource {\n /**\n * The context\n */\n private final SailPointContext context;\n\n /**\n * The Identity to use as the logged in user for this fake context\n */\n private final Identity loggedInUser;\n\n /**\n * The plugin name\n */\n private final String pluginName;\n\n /**\n * Constructs a new DummyPluginResource with the given auth data\n *\n * @param context The SailPointContext to return from {@link BasePluginResource#getContext()}\n * @param loggedInUser The Identity to return from various getLoggedIn... methods\n * @param pluginName The name of the plugin\n */\n public DummyPluginResource(SailPointContext context, Identity loggedInUser, String pluginName) {\n this.context = context;\n this.loggedInUser = loggedInUser;\n this.pluginName = pluginName;\n this.uriInfo = new DummyUriInfo();\n }\n\n /**\n * @see BasePluginResource#getContext()\n */\n @Override\n public SailPointContext getContext() {\n return context;\n }\n\n /**\n * @see BasePluginResource#getLoggedInUser()\n */\n @Override\n public Identity getLoggedInUser() throws GeneralException {\n return loggedInUser;\n }\n\n /**\n * @see BasePluginResource#getLoggedInUserCapabilities()\n */\n @Override\n public List<Capability> getLoggedInUserCapabilities() {\n List<Capability> capabilities = new ArrayList<>();\n try {\n capabilities.addAll(getLoggedInUser().getCapabilityManager().getEffectiveCapabilities());\n } catch(GeneralException e) {\n /* Ignore this */\n }\n return capabilities;\n }\n\n /**\n * @see BasePluginResource#getLoggedInUserName()\n */\n @Override\n public String getLoggedInUserName() throws GeneralException {\n return getLoggedInUser().getName();\n }\n\n /**\n * @see BasePluginResource#getLoggedInUserRights()\n */\n @Override\n public Collection<String> getLoggedInUserRights() {\n List<String> rights = new ArrayList<>();\n try {\n rights.addAll(getLoggedInUser().getCapabilityManager().getEffectiveFlattenedRights());\n } catch(GeneralException e) {\n /* Ignore this */\n }\n return rights;\n }\n\n /**\n * @see BasePluginResource#getPluginName()\n */\n @Override\n public String getPluginName() {\n return pluginName;\n }\n\n /**\n * @see BasePluginResource#getSettingBool(String)\n */\n @Override\n public boolean getSettingBool(String settingName) {\n if (Util.isNotNullOrEmpty(getPluginName())) {\n return super.getSettingBool(settingName);\n } else {\n return false;\n }\n }\n\n /**\n * @see BasePluginResource#getSettingInt(String)\n */\n @Override\n public int getSettingInt(String settingName) {\n if (Util.isNotNullOrEmpty(getPluginName())) {\n return super.getSettingInt(settingName);\n } else {\n return 0;\n }\n }\n\n /**\n * @see BasePluginResource#getSettingString(String)\n */\n @Override\n public String getSettingString(String settingName) {\n if (Util.isNotNullOrEmpty(getPluginName())) {\n return super.getSettingString(settingName);\n } else {\n return null;\n }\n }\n}" } ]
import com.identityworksllc.iiq.common.access.AccessCheckInput; import com.identityworksllc.iiq.common.access.AccessCheckResponse; import com.identityworksllc.iiq.common.auth.DummyPluginResource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import sailpoint.api.DynamicScopeMatchmaker; import sailpoint.api.Matchmaker; import sailpoint.api.SailPointContext; import sailpoint.object.Capability; import sailpoint.object.CustomGlobal; import sailpoint.object.DynamicScope; import sailpoint.object.Filter; import sailpoint.object.Identity; import sailpoint.object.IdentitySelector; import sailpoint.object.Script; import sailpoint.rest.plugin.BasePluginResource; import sailpoint.server.Environment; import sailpoint.tools.GeneralException; import sailpoint.tools.Util; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier;
5,868
if (Util.isNotNullOrEmpty(quicklinkPopulation)) { DynamicScopeMatchmaker dynamicScopeMatchmaker = new DynamicScopeMatchmaker(pluginContext.getContext()); DynamicScope dynamicScope = pluginContext.getContext().getObject(DynamicScope.class, quicklinkPopulation); boolean matchesDynamicScope = dynamicScopeMatchmaker.isMatch(dynamicScope, currentUser); if (matchesDynamicScope) { result.addMessage("Subject user matches DynamicScope " + quicklinkPopulation); DynamicScope.PopulationRequestAuthority populationRequestAuthority = dynamicScope.getPopulationRequestAuthority(); if (populationRequestAuthority != null && !populationRequestAuthority.isAllowAll()) { matchesDynamicScope = dynamicScopeMatchmaker.isMember(currentUser, target, populationRequestAuthority); } } if (!matchesDynamicScope) { result.denyMessage("Access denied to " + thingName + " because QuickLink population " + quicklinkPopulation + " does not match the subject and target"); } } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedRights())) { boolean userAllowed = true; List<String> rights = config.getValidTargetExcludedRights(); Collection<String> userRights = target.getCapabilityManager().getEffectiveFlattenedRights(); if (userRights != null) { for(String right : Util.safeIterable(userRights)) { if (rights.contains(right)) { result.addMessage("Excluded right matched: " + right); userAllowed = false; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded rights " + rights); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedCapabilities())) { boolean userAllowed = true; List<String> rights = config.getValidTargetExcludedCapabilities(); List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities(); if (capabilities != null) { for(Capability capability : Util.safeIterable(capabilities)) { if (rights.contains(capability.getName())) { result.addMessage("Excluded capability matched: " + capability.getName()); userAllowed = false; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded capabilities " + rights); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getInvalidTargetFilter())) { String filterString = config.getValidTargetFilter(); Filter compiledFilter = Filter.compile(filterString); HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter); if (hom.matches(target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches the invalid target filter"); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetWorkgroups())) { List<String> workgroups = config.getValidTargetWorkgroups(); boolean userAllowed = matchesAnyWorkgroup(target, workgroups); if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match any of the required workgroups " + workgroups); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetCapabilities())) { boolean userAllowed = false; List<String> rights = config.getValidTargetCapabilities(); List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities(); if (capabilities != null) { for(Capability capability : Util.safeIterable(capabilities)) { if (rights.contains(capability.getName())) { userAllowed = true; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match one or more of the included capabilities " + rights); } } if (result.isAllowed() && config.getValidTargetSelector() != null) { IdentitySelector selector = config.getValidTargetSelector(); Matchmaker matchmaker = new Matchmaker(pluginContext.getContext()); if (!matchmaker.isMatch(selector, target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target selector"); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getValidTargetFilter())) { String filterString = config.getValidTargetFilter(); Filter compiledFilter = Filter.compile(filterString); HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter); if (!hom.matches(target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target filter"); } } return result; } /** * An optional clear-cache method that can be used by plugin code */ public static void clearCachedResults() { ConcurrentHashMap<SecurityCacheToken, SecurityResult> cacheMap = getCacheMap(); cacheMap.clear(); } /** * Creates a fake plugin context for use with {@link ThingAccessUtils#checkThingAccess(BasePluginResource, Identity, String, Map)} outside of a plugin. This constructs a new instance of a dummy BasePluginResource web service endpoint class. * @param context The SailPointContext to return from {@link BasePluginResource#getContext()} * @param loggedInUser The Identity to return from various getLoggedIn... methods * @param pluginName The name of the plugin to include in the fake plugin context * @return The fake plugin resource */ public static BasePluginResource createFakePluginContext(final SailPointContext context, final Identity loggedInUser, String pluginName) {
package com.identityworksllc.iiq.common; /** * Implements the "Common Security" protocol that was originally part of the * UPE plugin. This allows more detailed authorization to check access to * various objects within IIQ. * * There are two users involved in thing access: an subject Identity and a target * Identity. The subject is the one doing the thing while the target is the one * the thing is being done to. Some actions may be 'self' actions, where both the * subject and the target are the same. Other actions don't have a 'target' concept * and are treated as 'self' actions. */ @SuppressWarnings("unused") public class ThingAccessUtils { /** * The container object to hold the cached ThingAccessUtil results */ private static final class SecurityResult implements Supplier<Optional<AccessCheckResponse>> { /** * The epoch millisecond timestamp when this object expires, one minute after creation */ private final long expiration; /** * The actual cached result */ private final Object result; /** * Store the result with an expiration time * @param result The result to cache */ public SecurityResult(AccessCheckResponse result) { this.result = result; this.expiration = System.currentTimeMillis() + (1000L * 60); } /** * Returns the cached result * @return The cached result */ public Optional<AccessCheckResponse> get() { if (this.result instanceof AccessCheckResponse && !this.isExpired()) { return Optional.of((AccessCheckResponse) this.result); } else { return Optional.empty(); } } /** * Returns true if the current epoch timestamp is later than the expiration date * @return True if expired */ private boolean isExpired() { return System.currentTimeMillis() >= expiration; } } /** * The container object to identify the cached ThingAccessUtil inputs. * * NOTE: It is very important that this work properly across plugin * classloader contexts, even if the plugin has its own version of * ThingAccessUtils. */ public static final class SecurityCacheToken { /** * The CommonSecurityConfig object associated with the cached result */ private final Map<String, Object> commonSecurityConfig; /** * The version of the plugin cache to invalidate records whenever * a new plugin is installed. This will prevent wacky class cast * problems. */ private final int pluginVersion; /** * The name of the source identity */ private final String source; /** * The optional state map */ private final Map<String, Object> state; /** * The name of the target identity */ private final String target; /** * Constructs a new cache entry * @param csc The security config * @param source The source identity name * @param target The target identity name */ public SecurityCacheToken(CommonSecurityConfig csc, String source, String target, Map<String, Object> state) { this.commonSecurityConfig = csc.toMap(); this.target = target; this.source = source; this.state = new HashMap<>(); if (state != null) { this.state.putAll(state); } this.pluginVersion = Environment.getEnvironment().getPluginsCache().getVersion(); } /** * Constructs a new cache entry based on the input * @param input The input object * @throws GeneralException the errors */ public SecurityCacheToken(AccessCheckInput input) throws GeneralException { this( input.getConfiguration(), input.getPluginResource().getLoggedInUserName(), (input.getTarget() == null || input.getTarget().getName() == null) ? "null" : input.getTarget().getName(), input.getState() ); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SecurityCacheToken that = (SecurityCacheToken) o; return this.pluginVersion == that.pluginVersion && Objects.equals(commonSecurityConfig, that.commonSecurityConfig) && Objects.equals(target, that.target) && Objects.equals(source, that.source) && Objects.equals(state, that.state); } @Override public int hashCode() { return Objects.hash(pluginVersion, commonSecurityConfig, target, source, state); } } private static final String CACHE_KEY = "idw.ThingAccessUtils.cache"; /** * The logger */ private static final Log log = LogFactory.getLog(ThingAccessUtils.class); /** * Returns true if the logged in user can access the item based on the Common Security configuration parameters. * * @param pluginContext The plugin context, which provides user details * @param configuration The configuration for the field or button or other object * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static boolean checkThingAccess(BasePluginResource pluginContext, Map<String, Object> configuration) throws GeneralException { return checkThingAccess(pluginContext, null, "anonymous", configuration); } /** * Returns true if the logged in user can access the item based on the CommonSecurityConfig object * * @param pluginContext The plugin context, which provides user details * @param config the CommonSecurityConfig object * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static boolean checkThingAccess(BasePluginResource pluginContext, CommonSecurityConfig config) throws GeneralException { return checkThingAccess(pluginContext, null, "anonymous", config); } /** * Returns true if the logged in user can access the item based on the common configuration parameters. * * @param pluginContext The plugin context, which provides user details * @param targetIdentity The target identity for the action (as opposed to the actor) * @param configuration The configuration for the field or button or other object * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static boolean checkThingAccess(BasePluginResource pluginContext, Identity targetIdentity, Map<String, Object> configuration) throws GeneralException { return checkThingAccess(pluginContext, targetIdentity, "anonymous", configuration); } /** * Returns true if the logged in user can access the item based on the common configuration parameters. * * @param pluginContext A plugin REST API resource (or fake equivalent) used to get some details and settings. This must not be null. * @param targetIdentity The target identity * @param thingName The thing being checked * @param configuration The configuration for the field or button or other object * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static boolean checkThingAccess(BasePluginResource pluginContext, Identity targetIdentity, String thingName, Map<String, Object> configuration) throws GeneralException { Identity currentUser = pluginContext.getLoggedInUser(); Identity target = targetIdentity; if (target == null) { target = currentUser; } if (configuration == null || configuration.isEmpty()) { log.debug("Configuration for " + thingName + " is empty; assuming that access is allowed"); return true; } CommonSecurityConfig config = CommonSecurityConfig.decode(configuration); return checkThingAccess(pluginContext, target, thingName, config); } /** * Returns true if the logged in user can access the item based on the common configuration parameters. * * Results for the same CommonSecurityConfig, source, and target user will be cached for up to one minute * unless the CommonSecurityConfig object has noCache set to true. * * @param pluginContext A plugin REST API resource (or fake equivalent) used to get some details and settings. This must not be null. * @param target The target identity * @param thingName The thing being checked, entirely for logging purposes * @param config The configuration specifying security rights * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static boolean checkThingAccess(BasePluginResource pluginContext, Identity target, String thingName, CommonSecurityConfig config) throws GeneralException { AccessCheckInput input = new AccessCheckInput(pluginContext, target, thingName, config); return checkThingAccess(input).isAllowed(); } /** * Returns an 'allowed' response if the logged in user can access the item based on the * common configuration parameters. * * Results for the same CommonSecurityConfig, source, and target user will be cached for up to one minute * unless the CommonSecurityConfig object has noCache set to true. * * @param input The input containing the configuration for the checkThingAccess utility * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ public static AccessCheckResponse checkThingAccess(AccessCheckInput input) throws GeneralException { if (input.getConfiguration() == null) { throw new IllegalArgumentException("An access check must contain a CommonSecurityConfig"); } if (input.getPluginResource() == null) { throw new IllegalArgumentException("An access check must contain a plugin context for accessing the IIQ context and the logged in user"); } AccessCheckResponse result; try { if (!input.getConfiguration().isNoCache()) { SecurityCacheToken cacheToken = new SecurityCacheToken(input); Optional<AccessCheckResponse> cachedResult = getCachedResult(cacheToken); if (cachedResult.isPresent()) { return cachedResult.get(); } result = checkThingAccessImpl(input, null); getCacheMap().put(cacheToken, new SecurityResult(result)); } else { result = checkThingAccessImpl(input, null); } } catch(Exception e) { result = new AccessCheckResponse(); result.denyMessage("Caught an exception evaluating criteria: " + e.getMessage()); log.error("Caught an exception evaluating access criteria", e); } return result; } /** * Returns an allowed response if the logged in user can access the item based on * the common configuration parameters. * * @param input The inputs to the access check * @return True if the user has access to the thing based on the configuration * @throws GeneralException if any check failures occur (this should be interpreted as "no access") */ private static AccessCheckResponse checkThingAccessImpl(final AccessCheckInput input, AccessCheckResponse result) throws GeneralException { if (result == null) { result = new AccessCheckResponse(); } BasePluginResource pluginContext = input.getPluginResource(); final Identity currentUser = pluginContext.getLoggedInUser(); final Identity target = (input.getTarget() != null) ? input.getTarget() : currentUser; final String currentUserName = pluginContext.getLoggedInUserName(); final CommonSecurityConfig config = input.getConfiguration(); final String thingName = input.getThingName(); if (config.isDisabled()) { result.denyMessage("Access denied to " + thingName + " because the configuration is marked disabled"); } if (result.isAllowed() && Utilities.isNotEmpty(config.getOneOf())) { boolean anyMatch = false; for(CommonSecurityConfig sub : config.getOneOf()) { AccessCheckInput child = new AccessCheckInput(input, sub); AccessCheckResponse childResponse = checkThingAccessImpl(child, null); if (childResponse.isAllowed()) { anyMatch = true; break; } } if (!anyMatch) { result.denyMessage("Access denied to " + thingName + " because none of the items in the 'oneOf' list resolved to true"); } } if (result.isAllowed() && Utilities.isNotEmpty(config.getAllOf())) { boolean allMatch = true; for(CommonSecurityConfig sub : config.getAllOf()) { AccessCheckInput child = new AccessCheckInput(input, sub); AccessCheckResponse childResponse = checkThingAccessImpl(child, null); if (!childResponse.isAllowed()) { allMatch = false; break; } } if (!allMatch) { result.denyMessage("Access denied to " + thingName + " because at least one of the items in the 'allOf' list resolved to 'deny'"); } } if (result.isAllowed() && Utilities.isNotEmpty(config.getNot())) { boolean anyMatch = false; for(CommonSecurityConfig sub : config.getNot()) { AccessCheckInput child = new AccessCheckInput(input, sub); AccessCheckResponse childResponse = checkThingAccessImpl(child, null); if (childResponse.isAllowed()) { anyMatch = true; break; } } if (anyMatch) { result.denyMessage("Access denied to " + thingName + " because at least one of the items in the 'not' list resolved to 'allow'"); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getSettingOffSwitch())) { boolean isDisabled = pluginContext.getSettingBool(config.getSettingOffSwitch()); if (isDisabled) { result.denyMessage("Access denied to " + thingName + " because the feature " + config.getSettingOffSwitch() + " is disabled in plugin settings"); } } if (result.isAllowed() && config.getAccessCheckScript() != null) { Script script = Utilities.getAsScript(config.getAccessCheckScript()); Map<String, Object> scriptArguments = new HashMap<>(); scriptArguments.put("subject", currentUser); scriptArguments.put("target", target); scriptArguments.put("requester", currentUser); scriptArguments.put("identity", target); scriptArguments.put("identityName", target.getName()); scriptArguments.put("manager", target.getManager()); scriptArguments.put("context", pluginContext.getContext()); scriptArguments.put("log", LogFactory.getLog(pluginContext.getClass())); scriptArguments.put("state", input.getState()); Object output = pluginContext.getContext().runScript(script, scriptArguments); // If the script returns a non-null value, it will be considered the authoritative // response. No further checks will be done. If the output is null, the access // checks will defer farther down. if (output != null) { boolean userAllowed = Util.otob(output); if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because access check script returned false for subject user " + currentUserName); } return result; } } if (result.isAllowed() && config.getAccessCheckRule() != null) { Map<String, Object> scriptArguments = new HashMap<>(); scriptArguments.put("subject", currentUser); scriptArguments.put("target", target); scriptArguments.put("requester", currentUser); scriptArguments.put("identity", target); scriptArguments.put("identityName", target.getName()); scriptArguments.put("manager", target.getManager()); scriptArguments.put("context", pluginContext.getContext()); scriptArguments.put("log", LogFactory.getLog(pluginContext.getClass())); scriptArguments.put("state", input.getState()); Object output = pluginContext.getContext().runRule(config.getAccessCheckRule(), scriptArguments); // If the script returns a non-null value, it will be considered the authoritative // response. No further checks will be done. If the output is null, the access // checks will defer farther down. if (output != null) { boolean userAllowed = Util.otob(output); if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because access check rule returned false for subject user " + currentUserName); } return result; } } if (result.isAllowed() && !Util.isEmpty(config.getRequiredRights())) { boolean userAllowed = false; List<String> rights = config.getRequiredRights(); Collection<String> userRights = pluginContext.getLoggedInUserRights(); if (userRights != null) { for(String right : Util.safeIterable(userRights)) { if (rights.contains(right)) { result.addMessage("Matching SPRight: " + right); userAllowed = true; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of the required rights " + rights); } } if (result.isAllowed() && !Util.isEmpty(config.getRequiredCapabilities())) { boolean userAllowed = false; List<String> capabilities = config.getRequiredCapabilities(); List<Capability> loggedInUserCapabilities = pluginContext.getLoggedInUserCapabilities(); for(Capability cap : Util.safeIterable(loggedInUserCapabilities)) { if (capabilities.contains(cap.getName())) { result.addMessage("Matching Capability: " + cap.getName()); userAllowed = true; break; } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of these required capabilities " + capabilities); } } if (result.isAllowed() && !Util.isEmpty(config.getExcludedRights())) { boolean userAllowed = true; List<String> rights = config.getRequiredRights(); Collection<String> userRights = pluginContext.getLoggedInUserRights(); if (userRights != null) { for(String right : Util.safeIterable(userRights)) { if (rights.contains(right)) { result.addMessage("Matching excluded SPRight: " + right); userAllowed = false; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " matches one of these excluded SPRights: " + rights); } } if (result.isAllowed() && !Util.isEmpty(config.getExcludedCapabilities())) { boolean userAllowed = true; List<String> capabilities = config.getRequiredCapabilities(); List<Capability> loggedInUserCapabilities = pluginContext.getLoggedInUserCapabilities(); for(Capability cap : Util.safeIterable(loggedInUserCapabilities)) { if (capabilities.contains(cap.getName())) { result.addMessage("Matching excluded Capability: " + cap.getName()); userAllowed = false; break; } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " matches one of these excluded capabilities: " + capabilities); } } if (result.isAllowed() && !Util.isEmpty(config.getExcludedWorkgroups())) { List<String> workgroups = config.getExcludedWorkgroups(); boolean matchesWorkgroup = matchesAnyWorkgroup(currentUser, workgroups); if (matchesWorkgroup) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " is a member of an excluded workgroup in " + workgroups); } } if (result.isAllowed() && !Util.isEmpty(config.getRequiredWorkgroups())) { List<String> workgroups = config.getRequiredWorkgroups(); boolean userAllowed = matchesAnyWorkgroup(currentUser, workgroups); if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match any of the required workgroups " + workgroups); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getAccessCheckFilter())) { String filterString = config.getValidTargetFilter(); Filter compiledFilter = Filter.compile(filterString); HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter); if (!hom.matches(currentUser)) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match the access check filter"); } } if (result.isAllowed() && config.getAccessCheckSelector() != null) { IdentitySelector selector = config.getAccessCheckSelector(); Matchmaker matchmaker = new Matchmaker(pluginContext.getContext()); if (!matchmaker.isMatch(selector, currentUser)) { result.denyMessage("Access denied to " + thingName + " because subject user " + currentUserName + " does not match the access check selector"); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getMirrorQuicklinkPopulation())) { String quicklinkPopulation = config.getMirrorQuicklinkPopulation(); if (Util.isNotNullOrEmpty(quicklinkPopulation)) { DynamicScopeMatchmaker dynamicScopeMatchmaker = new DynamicScopeMatchmaker(pluginContext.getContext()); DynamicScope dynamicScope = pluginContext.getContext().getObject(DynamicScope.class, quicklinkPopulation); boolean matchesDynamicScope = dynamicScopeMatchmaker.isMatch(dynamicScope, currentUser); if (matchesDynamicScope) { result.addMessage("Subject user matches DynamicScope " + quicklinkPopulation); DynamicScope.PopulationRequestAuthority populationRequestAuthority = dynamicScope.getPopulationRequestAuthority(); if (populationRequestAuthority != null && !populationRequestAuthority.isAllowAll()) { matchesDynamicScope = dynamicScopeMatchmaker.isMember(currentUser, target, populationRequestAuthority); } } if (!matchesDynamicScope) { result.denyMessage("Access denied to " + thingName + " because QuickLink population " + quicklinkPopulation + " does not match the subject and target"); } } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedRights())) { boolean userAllowed = true; List<String> rights = config.getValidTargetExcludedRights(); Collection<String> userRights = target.getCapabilityManager().getEffectiveFlattenedRights(); if (userRights != null) { for(String right : Util.safeIterable(userRights)) { if (rights.contains(right)) { result.addMessage("Excluded right matched: " + right); userAllowed = false; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded rights " + rights); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetExcludedCapabilities())) { boolean userAllowed = true; List<String> rights = config.getValidTargetExcludedCapabilities(); List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities(); if (capabilities != null) { for(Capability capability : Util.safeIterable(capabilities)) { if (rights.contains(capability.getName())) { result.addMessage("Excluded capability matched: " + capability.getName()); userAllowed = false; break; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches one or more of the excluded capabilities " + rights); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getInvalidTargetFilter())) { String filterString = config.getValidTargetFilter(); Filter compiledFilter = Filter.compile(filterString); HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter); if (hom.matches(target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " matches the invalid target filter"); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetWorkgroups())) { List<String> workgroups = config.getValidTargetWorkgroups(); boolean userAllowed = matchesAnyWorkgroup(target, workgroups); if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match any of the required workgroups " + workgroups); } } if (result.isAllowed() && !Util.isEmpty(config.getValidTargetCapabilities())) { boolean userAllowed = false; List<String> rights = config.getValidTargetCapabilities(); List<Capability> capabilities = target.getCapabilityManager().getEffectiveCapabilities(); if (capabilities != null) { for(Capability capability : Util.safeIterable(capabilities)) { if (rights.contains(capability.getName())) { userAllowed = true; } } } if (!userAllowed) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match one or more of the included capabilities " + rights); } } if (result.isAllowed() && config.getValidTargetSelector() != null) { IdentitySelector selector = config.getValidTargetSelector(); Matchmaker matchmaker = new Matchmaker(pluginContext.getContext()); if (!matchmaker.isMatch(selector, target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target selector"); } } if (result.isAllowed() && Util.isNotNullOrEmpty(config.getValidTargetFilter())) { String filterString = config.getValidTargetFilter(); Filter compiledFilter = Filter.compile(filterString); HybridObjectMatcher hom = new HybridObjectMatcher(pluginContext.getContext(), compiledFilter); if (!hom.matches(target)) { result.denyMessage("Access denied to " + thingName + " because target user " + target.getName() + " does not match the valid target filter"); } } return result; } /** * An optional clear-cache method that can be used by plugin code */ public static void clearCachedResults() { ConcurrentHashMap<SecurityCacheToken, SecurityResult> cacheMap = getCacheMap(); cacheMap.clear(); } /** * Creates a fake plugin context for use with {@link ThingAccessUtils#checkThingAccess(BasePluginResource, Identity, String, Map)} outside of a plugin. This constructs a new instance of a dummy BasePluginResource web service endpoint class. * @param context The SailPointContext to return from {@link BasePluginResource#getContext()} * @param loggedInUser The Identity to return from various getLoggedIn... methods * @param pluginName The name of the plugin to include in the fake plugin context * @return The fake plugin resource */ public static BasePluginResource createFakePluginContext(final SailPointContext context, final Identity loggedInUser, String pluginName) {
return new DummyPluginResource(context, loggedInUser, pluginName);
2
2023-10-20 15:20:16+00:00
8k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/config/CFxdReceiverApp.java
[ { "identifier": "FxdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdRecord.java", "snippet": "public abstract class FxdRecord implements Serializable {\n\n /**\n * Time at record creation. [ns]\n */\n protected final long timeStamp;\n /**\n * Position at record creation.\n */\n protected final GeoPoint position;\n /**\n * Connection at record creation.\n */\n protected final String connectionId;\n /**\n * Speed at record creation. [m/s]\n */\n protected final double speed;\n /**\n * Distance driven on current connection. [m]\n */\n protected final double offset;\n /**\n * Heading of the unit. [°]\n */\n protected final double heading;\n\n /**\n * A {@link FxdRecord} represents a snapshot of a units current spatio-temporal data, including time, position, and connection id.\n * Based on a collection of these records, different traffic state estimation (TSE) algorithms can be applied\n */\n protected FxdRecord(long timeStamp, GeoPoint position, String connectionId, double speed, double offset, double heading) {\n this.timeStamp = timeStamp;\n this.position = position;\n this.connectionId = connectionId;\n this.speed = speed;\n this.offset = offset;\n this.heading = heading;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public GeoPoint getPosition() {\n return position;\n }\n\n public String getConnectionId() {\n return connectionId;\n }\n\n public double getSpeed() {\n return speed;\n }\n\n public double getOffset() {\n return offset;\n }\n\n public double getHeading() {\n return heading;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .appendSuper(super.toString())\n .append(\"timestamp\", timeStamp)\n .append(\"position\", position)\n .append(\"connectionId\", connectionId)\n .append(\"speed\", speed)\n .append(\"offset\", offset)\n .append(\"heading\", heading)\n .toString();\n }\n\n /**\n * Method that estimates the size in Bytes for an {@link FxdRecord}.\n */\n public long calculateRecordSize() {\n return 4L // time stamp\n + 8L * 3L // position (three doubles: lat, lon, ele)\n + 10L // average connection id 10 chars, 1 byte per char\n + 8L // speed\n + 8L // offset\n + 8L; // heading\n }\n\n /**\n * Interface for the record builder class. Concrete implementations will extend the {@link AbstractRecordBuilder}-class.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the record\n */\n public interface RecordBuilder<BuilderT extends RecordBuilder<BuilderT, RecordT>, RecordT extends FxdRecord> {\n\n BuilderT withOffset(double offset);\n\n BuilderT withSpeed(double speed);\n\n BuilderT withHeading(double heading);\n }\n}" }, { "identifier": "FxdTraversal", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdTraversal.java", "snippet": "public abstract class FxdTraversal<RecordT extends FxdRecord, TraversalT extends FxdTraversal<RecordT, TraversalT>> {\n\n protected final String connectionId;\n protected final List<RecordT> traversal;\n /**\n * Last record of previous traversal.\n */\n protected final RecordT previousRecord;\n /**\n * First record of previous following traversal.\n */\n protected final RecordT followingRecord;\n\n /**\n * Constructor for an {@link FxdTraversal}.\n */\n public FxdTraversal(String connectionId, List<RecordT> traversal, @Nullable RecordT previousRecord, @Nullable RecordT followingRecord) {\n this.connectionId = connectionId;\n this.traversal = traversal;\n this.previousRecord = previousRecord;\n this.followingRecord = followingRecord;\n }\n\n /**\n * Returns the id of the traversed connection.\n */\n public String getConnectionId() {\n return connectionId;\n }\n\n /**\n * Returns a list of all {@link RecordT Records} on the traversed connection.\n */\n public List<RecordT> getTraversal() {\n return traversal;\n }\n\n /**\n * Returns the last record of the previous traversal.\n * Note: {@link RecordT#getConnectionId()} will be different from {@link #getConnectionId()}\n */\n @Nullable\n public RecordT getPreviousRecord() {\n return previousRecord;\n }\n\n /**\n * Returns the first record of the following traversal.\n * Note: {@link RecordT#getConnectionId()} will be different from {@link #getConnectionId()}\n */\n @Nullable\n public RecordT getFollowingRecord() {\n return followingRecord;\n }\n\n /**\n * Method to create a deep copy of the {@link FxdTraversal}, needs to be implemented by child classes.\n */\n public abstract TraversalT copy();\n}" }, { "identifier": "FxdUpdateMessage", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/messages/FxdUpdateMessage.java", "snippet": "public abstract class FxdUpdateMessage<RecordT extends FxdRecord> extends V2xMessage {\n\n private final long timeStamp;\n private final SortedMap<Long, RecordT> records;\n private final boolean isFinal;\n\n protected FxdUpdateMessage(MessageRouting messageRouting, long timeStamp, SortedMap<Long, RecordT> records, boolean isFinal) {\n super(messageRouting);\n this.timeStamp = timeStamp;\n this.records = records;\n this.isFinal = isFinal;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public final SortedMap<Long, RecordT> getRecords() {\n // always return copy of records, in case list is processed by multiple processors\n return Maps.newTreeMap(records);\n }\n\n public boolean isFinal() {\n return isFinal;\n }\n\n @Nonnull\n @Override\n public EncodedPayload getPayLoad() {\n return new EncodedPayload(calculateMessageLength());\n }\n\n /**\n * Method that estimates the length of an average {@link FxdUpdateMessage UpdateMessage} adding the baseline length of required fields with\n * the length of the specialized {@link FxdUpdateMessage FxdUpdateMessages}.\n */\n public long calculateMessageLength() {\n return 10 // \"header size\"\n + 8 // for time stamp\n + 1 // for isFinal flag\n + getRecords().values().stream().mapToLong(FxdRecord::calculateRecordSize).sum(); // size for each record\n }\n\n /**\n * Interface for the builder of {@link FxdUpdateMessage FxdUpdateMessages}.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the records\n * @param <UpdateT> concrete type of the updates being built\n */\n interface FxdUpdateMessageBuilder<\n BuilderT extends FxdUpdateMessageBuilder<BuilderT, RecordT, UpdateT>,\n RecordT extends FxdRecord,\n UpdateT extends FxdUpdateMessage<RecordT>> {\n\n BuilderT addRecords(SortedMap<Long, RecordT> records);\n\n BuilderT isFinal();\n }\n\n}" }, { "identifier": "FxdKernel", "path": "src/main/java/com/dcaiti/mosaic/app/tse/FxdKernel.java", "snippet": "public abstract class FxdKernel<\n RecordT extends FxdRecord,\n TraversalT extends FxdTraversal<RecordT, TraversalT>,\n UpdateT extends FxdUpdateMessage<RecordT>,\n ConfigT extends CFxdReceiverApp<RecordT, TraversalT, UpdateT>>\n implements EventProcessor {\n private final EventManager eventManager;\n protected final UnitLogger logger;\n /**\n * Field holding the configuration to\n * See: {@link CFxdReceiverApp}\n */\n protected final ConfigT config;\n /**\n * A Map containing all known senders and all received records, that haven't been processed yet.\n * The value of this map is as {@link SortedMap}, which uses the time of record creation as key, which allows for easy\n * garbage collection.\n */\n private final Map<String, SortedMap<Long, RecordT>> recordBuffer = new HashMap<>();\n /**\n * A map to store all traversed connections of a sender.\n */\n private final Map<String, List<String>> connectionsBuffer = new HashMap<>();\n /**\n * A look back to store the last record of a previous traversal if that should be required in a processor.\n */\n private final Map<String, RecordT> recordLookBack = new HashMap<>();\n protected final List<FxdProcessor> allProcessors;\n private final List<TraversalBasedProcessor<RecordT, TraversalT>> traversalBasedProcessors = new ArrayList<>();\n private final List<MessageBasedProcessor> messageBasedProcessors = new ArrayList<>();\n /**\n * A registry holding all time based processors with identifiable keys (i.e., their class names) for event handling.\n * Note that this implicates that only one of each {@link TimeBasedProcessor} type can be used in the same simulation.\n */\n private final Map<String, TimeBasedProcessor<RecordT, UpdateT>> timeBasedProcessors = new HashMap<>();\n private long lastRemovalTime = 0;\n private long oldestAllowedRecordTime = 0;\n\n /**\n * Constructor for the {@link FxdKernel} initializing the {@link FxdProcessor FxdProcessors} and setting the event manager and logger.\n *\n * @param eventManager used for managing event handling for configured {@link FxdProcessor FxdProcessors} and\n * the removal of expired units of the {@link #recordBuffer}\n * @param logger for logging purposes, gets forwarded to {@link FxdProcessor FxdProcessors}\n * @param config configuration of the application\n */\n public FxdKernel(EventManager eventManager, UnitLogger logger, ConfigT config) {\n this.eventManager = eventManager;\n this.logger = logger;\n this.config = config;\n if (config.traversalBasedProcessors != null) {\n this.traversalBasedProcessors.addAll(config.traversalBasedProcessors);\n }\n if (config.timeBasedProcessors != null) {\n // create registry of time based processors\n config.timeBasedProcessors.forEach(processor -> {\n if (processor.triggerInterval >= 0) { // validate that processor has a legal trigger interval\n this.timeBasedProcessors.put(processor.getIdentifier(), processor);\n }\n });\n }\n if (config.messageBasedProcessors != null) {\n messageBasedProcessors.addAll(config.messageBasedProcessors);\n }\n allProcessors = combineAllFxdProcessors();\n allProcessors.forEach(processor -> processor.initialize(logger));\n // initial event scheduling\n timeBasedProcessors.forEach((name, processor) -> scheduleEventForTimeBasedProcessor(processor));\n scheduleUnitRemoval();\n }\n\n private List<FxdProcessor> combineAllFxdProcessors() {\n final List<FxdProcessor> allProcessors;\n allProcessors = new ArrayList<>();\n allProcessors.addAll(timeBasedProcessors.values());\n allProcessors.addAll(traversalBasedProcessors);\n allProcessors.addAll(messageBasedProcessors);\n return allProcessors;\n }\n\n /**\n * This is method is the link between the kernel and the application, handling the updates for both the\n * {@link TimeBasedProcessor TimeBasedProcessors} and the {@link TraversalBasedProcessor TraversalBasedProcessors}.\n *\n * @param update the received update\n */\n public void processUpdate(UpdateT update) {\n // time-based processors will keep their own representation of\n timeBasedProcessors.values().forEach(processor -> processor.handleUpdate(update));\n processUpdateForTraversals(update);\n additionalProcessingOfUpdate(update); // implementation-specific handling of update\n if (update.isFinal()) { // remove sender after it was processed for last traversal\n String unitName = update.getRouting().getSource().getSourceName();\n recordBuffer.remove(unitName);\n recordLookBack.remove(unitName);\n connectionsBuffer.remove(unitName);\n }\n }\n\n private void processUpdateForTraversals(FxdUpdateMessage<RecordT> fxdUpdateMessage) {\n String senderId = fxdUpdateMessage.getRouting().getSource().getSourceName();\n List<String> senderConnections = extractTraversedConnections(senderId, fxdUpdateMessage.getRecords());\n SortedMap<Long, RecordT> senderRecords = enqueueRecords(senderId, fxdUpdateMessage.getRecords());\n // if there is more than one connection, we know there is a completed traversal\n while (senderConnections.size() > 1) { // we cannot be sure that only on connection has been traversed in the last update\n TraversalT traversal = extractTraversal(senderId, senderConnections.get(0), senderRecords);\n logger.debug(\"Handling traversal for vehicle: {} on connection {}\", senderId, traversal.getConnectionId());\n triggerTraversalBasedProcessors(senderId, traversal);\n senderConnections.remove(0); // traversal has been processed\n }\n }\n\n /**\n * This method extracts a sorted list in order of a vehicle's route containing all non-processed connection traversals.\n *\n * @param senderId id of the sender\n * @param records the newly received records\n * @return an ordered (by route) list of traversed connections\n */\n private List<String> extractTraversedConnections(String senderId, SortedMap<Long, RecordT> records) {\n if (!connectionsBuffer.containsKey(senderId)) { // on first record of a vehicle add it\n RecordT firstRecord = records.get(records.firstKey());\n connectionsBuffer.put(senderId, Lists.newArrayList(firstRecord.getConnectionId()));\n }\n // scan records for all traversed connections\n List<String> senderConnections = connectionsBuffer.get(senderId);\n records.values().forEach(record -> {\n if (!senderConnections.contains(record.getConnectionId())) {\n senderConnections.add(record.getConnectionId());\n }\n });\n return senderConnections;\n }\n\n /**\n * Method that extracts traversal from received {@link RecordT records} and bundles them in a {@link TraversalT traversal} object.\n *\n * @param senderId the id of the unit that has been recognized to traverse a connection\n * @param currentConnectionId the traversed connection\n * @param senderRecords all relevant {@link RecordT records} for the traversals\n * @return the extracted {@link TraversalT traversal}\n */\n private TraversalT extractTraversal(String senderId, String currentConnectionId, SortedMap<Long, RecordT> senderRecords) {\n // extract all entries on the earliest connection traversal\n List<RecordT> traversalRecords = new ArrayList<>();\n Long currentKey = senderRecords.firstKey();\n while (senderRecords.get(currentKey).getConnectionId().equals(currentConnectionId)) {\n traversalRecords.add(senderRecords.get(currentKey));\n senderRecords.remove(currentKey);\n currentKey = senderRecords.firstKey();\n }\n RecordT previousRecord = recordLookBack.get(senderId);\n RecordT followingRecord = senderRecords.get(currentKey);\n recordLookBack.put(senderId, traversalRecords.get(traversalRecords.size() - 1)); // save last record of traversal for next traversal\n return createTraversal(traversalRecords, previousRecord, followingRecord);\n }\n\n private void triggerTraversalBasedProcessors(String senderId, TraversalT traversal) {\n // handle traversal for all traversal based processors\n traversalBasedProcessors.forEach(processor -> processor.onConnectionTraversal(senderId, traversal.copy()));\n }\n\n private SortedMap<Long, RecordT> enqueueRecords(String senderId, SortedMap<Long, RecordT> records) {\n if (recordBuffer.containsKey(senderId)) {\n recordBuffer.get(senderId).putAll(records);\n } else {\n recordBuffer.putIfAbsent(senderId, records);\n }\n return recordBuffer.get(senderId);\n }\n\n @Override\n public void processEvent(Event event) {\n if (event instanceof ExpiredUnitRemovalEvent) {\n triggerExpiredUnitRemoval(oldestAllowedRecordTime);\n } else {\n Object resource = event.getResource();\n if (resource instanceof String) {\n String processorName = (String) resource;\n if (timeBasedProcessors.containsKey(processorName)) {\n TimeBasedProcessor<RecordT, UpdateT> processor = timeBasedProcessors.get(processorName);\n processor.triggerEvent(event.getTime());\n scheduleEventForTimeBasedProcessor(processor);\n } else {\n logger.debug(\"No Processor named {} initialized\", processorName);\n }\n }\n\n }\n }\n\n private void scheduleEventForTimeBasedProcessor(TimeBasedProcessor<RecordT, UpdateT> timeBasedProcessor) {\n eventManager.newEvent(timeBasedProcessor.getAndIncrementNextTriggerTime(), this)\n .withResource(timeBasedProcessor.getIdentifier()).withNice(0).schedule();\n }\n\n /**\n * This method acts as a garbage collection for units that didn't send any records since the specified time.\n *\n * @param oldestAllowedRecordTime if all records of a unit are older than this, we assume the unit is no longer sending\n */\n private void triggerExpiredUnitRemoval(Long oldestAllowedRecordTime) {\n List<String> unitsToRemove = new ArrayList<>();\n for (Map.Entry<String, SortedMap<Long, RecordT>> entry : recordBuffer.entrySet()) {\n if (entry.getValue().lastKey() < oldestAllowedRecordTime) {\n unitsToRemove.add(entry.getKey());\n }\n }\n logger.debug(\"Removing units due to inactivity: {}\", unitsToRemove);\n unitsToRemove.forEach(unit -> {\n recordBuffer.remove(unit);\n connectionsBuffer.remove(unit);\n });\n }\n\n private void scheduleUnitRemoval() {\n lastRemovalTime += config.unitRemovalInterval;\n oldestAllowedRecordTime += config.unitExpirationTime;\n ExpiredUnitRemovalEvent expiredUnitRemovalEvent = new ExpiredUnitRemovalEvent(lastRemovalTime, this);\n eventManager.addEvent(expiredUnitRemovalEvent);\n }\n\n /**\n * Handles the triggering of the {@link #messageBasedProcessors} if the {@link V2xMessage} is of the correct type.\n *\n * @param receivedV2xMessage message forwarded by the {@link FxdReceiverApp}\n * @param responseRouting {@link MessageRouting} pointing back to the original sender (Required for building the response)\n */\n public List<V2xMessage> handleMessageAdvanced(ReceivedV2xMessage receivedV2xMessage, MessageRouting responseRouting) {\n List<V2xMessage> responses = new ArrayList<>();\n List<MessageBasedProcessor> handlingProcessors = messageBasedProcessors.stream()\n .filter(processor -> processor.isInstanceOfMessage(receivedV2xMessage))\n .collect(Collectors.toList());\n if (handlingProcessors.isEmpty()) { // check if message can be handled by any processors\n logger.debug(\"No Processor found to handle message of type {}\", receivedV2xMessage.getMessage().getClass());\n }\n handlingProcessors.forEach(processor -> {\n V2xMessage response = processor.handleReceivedMessage(receivedV2xMessage, responseRouting);\n if (response != null) {\n responses.add(response);\n }\n });\n return responses;\n }\n\n /**\n * This method triggers the {@code shutdown} methods of all configured {@link FxdProcessor FxdProcessors} and cleans up any buffers.\n *\n * @param shutdownTime time of kernel shutdown\n */\n public void shutdown(long shutdownTime) {\n for (FxdProcessor processor : allProcessors) {\n processor.shutdown(shutdownTime);\n }\n recordBuffer.clear();\n connectionsBuffer.clear();\n }\n\n /**\n * This method is used for specialized handling of {@link UpdateT updates} that is outside the scope of the {@link FxdKernel}\n * implementation.\n *\n * @param update an extension of {@link FxdUpdateMessage} received from a unit\n */\n protected abstract void additionalProcessingOfUpdate(UpdateT update);\n\n protected abstract TraversalT createTraversal(\n List<RecordT> traversalRecords,\n @Nullable RecordT previousRecord,\n @Nullable RecordT followingRecord\n );\n}" }, { "identifier": "MessageBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/MessageBasedProcessor.java", "snippet": "@JsonAdapter(MessageBasedProcessorTypeAdapterFactory.class)\npublic interface MessageBasedProcessor extends FxdProcessor {\n\n /**\n * Handles the reception of {@link V2xMessage V2xMessages} that clear the {@link #isInstanceOfMessage} check.\n * Furthermore, this method allows building a response, which will be transmitted to the sender of the\n * original message.\n *\n * @param message the message container including a {@link V2xMessage} and additional information\n * @param responseRouting {@link MessageRouting} pointing back to the original sender (Required for building the response)\n * @return A response in the form of a {@link V2xMessage}\n */\n V2xMessage handleReceivedMessage(ReceivedV2xMessage message, MessageRouting responseRouting);\n\n /**\n * This method is used to validate that a {@link MessageBasedProcessor} can handle the specified message.\n * Implementations will usually look like {@code message.getMessage() instanceof <message-type>}\n *\n * @param message the message to check\n * @return a flag indicating whether the message can be processed or not\n */\n boolean isInstanceOfMessage(ReceivedV2xMessage message);\n}" }, { "identifier": "TimeBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/TimeBasedProcessor.java", "snippet": "@JsonAdapter(TimeBasedProcessorTypeAdapterFactory.class)\npublic abstract class TimeBasedProcessor<RecordT extends FxdRecord, UpdateT extends FxdUpdateMessage<RecordT>> implements FxdProcessor {\n\n /**\n * Sets the time interval at which the {@link #triggerEvent} function is being called.\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public long triggerInterval = 30 * TIME.MINUTE;\n /**\n * Logger class that allows writing to application logs.\n */\n protected UnitLogger logger;\n private long nextTriggerTime;\n private long previousTriggerTime;\n\n @Override\n public void initialize(UnitLogger logger) {\n this.logger = logger;\n previousTriggerTime = 0;\n nextTriggerTime = 0;\n }\n\n public long getAndIncrementNextTriggerTime() {\n previousTriggerTime = nextTriggerTime;\n return nextTriggerTime += triggerInterval;\n }\n\n public long getPreviousTriggerTime() {\n return previousTriggerTime;\n }\n\n public abstract String getIdentifier();\n\n public abstract void handleUpdate(UpdateT update);\n\n /**\n * This method will handle the execution of the event.\n * And will be called by the kernel based on {@link #triggerInterval}.\n *\n * @param eventTime simulation time at event trigger\n */\n public abstract void triggerEvent(long eventTime);\n\n\n @SuppressWarnings(\"rawtypes\")\n public static String createIdentifier(Class<? extends TimeBasedProcessor> processorClass) {\n return ClassUtils.getShortClassName(processorClass);\n }\n}" }, { "identifier": "TraversalBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/TraversalBasedProcessor.java", "snippet": "@JsonAdapter(TraversalBasedProcessorTypeAdapterFactory.class)\npublic interface TraversalBasedProcessor<RecordT extends FxdRecord, TraversalT extends FxdTraversal<RecordT, TraversalT>>\n extends FxdProcessor {\n\n void onConnectionTraversal(String unitId, TraversalT traversal);\n}" } ]
import com.dcaiti.mosaic.app.fxd.data.FxdRecord; import com.dcaiti.mosaic.app.fxd.data.FxdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage; import com.dcaiti.mosaic.app.tse.FxdKernel; import com.dcaiti.mosaic.app.tse.processors.MessageBasedProcessor; import com.dcaiti.mosaic.app.tse.processors.TimeBasedProcessor; import com.dcaiti.mosaic.app.tse.processors.TraversalBasedProcessor; import org.eclipse.mosaic.lib.util.gson.TimeFieldAdapter; import org.eclipse.mosaic.rti.TIME; import com.google.gson.annotations.JsonAdapter; import java.util.List;
5,927
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: [email protected] */ package com.dcaiti.mosaic.app.tse.config; public class CFxdReceiverApp< RecordT extends FxdRecord,
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: [email protected] */ package com.dcaiti.mosaic.app.tse.config; public class CFxdReceiverApp< RecordT extends FxdRecord,
TraversalT extends FxdTraversal<RecordT, TraversalT>,
1
2023-10-23 16:39:40+00:00
8k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java
[ { "identifier": "AgnidusAgateBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateBlock.java", "snippet": "public class AgnidusAgateBlock extends Block {\n public AgnidusAgateBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 18f).requiresCorrectToolForDrops().noOcclusion().isRedstoneConductor((bs, br, bp) -> false));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n\n @Override\n public @NotNull VoxelShape getVisualShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {\n return Shapes.empty();\n }\n\n @Override\n public void stepOn(Level world, BlockPos pos, BlockState blockstate, Entity entity) {\n super.stepOn(world, pos, blockstate, entity);\n entity.setSecondsOnFire(15);\n }\n}" }, { "identifier": "AgnidusAgateOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateOreBlock.java", "snippet": "public class AgnidusAgateOreBlock extends Block {\n public AgnidusAgateOreBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.NETHER_ORE).strength(1f, 5f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.agnidus_agate_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "NagadusEmeraldBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/nagadus/NagadusEmeraldBlock.java", "snippet": "public class NagadusEmeraldBlock extends Block {\n public NagadusEmeraldBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 15f));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "NagadusEmeraldOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/nagadus/NagadusEmeraldOreBlock.java", "snippet": "public class NagadusEmeraldOreBlock extends Block implements BlockExtension {\n public NagadusEmeraldOreBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GRAVEL).strength(2f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.nagadus_emerald_ore.line1\"));\n }\n\n @Override\n public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing) {\n return true;\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n\n @Override\n public void onDestroyedByPlayer(Level level, Player player, BlockPos pos, BlockState state, BlockEntity blockEntity, ItemStack tool) {\n if (!level.isClientSide()) {\n level.playSound(null, pos, SoundEvents.GLASS_BREAK, SoundSource.BLOCKS, (float) 0.5, 1);\n }\n }\n}" }, { "identifier": "PrithvaTopazBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/prithva/PrithvaTopazBlock.java", "snippet": "public class PrithvaTopazBlock extends Block {\n public PrithvaTopazBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 100f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.prithva_topaz_block.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "PrithvaTopazOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/prithva/PrithvaTopazOreBlock.java", "snippet": "public class PrithvaTopazOreBlock extends Block {\n public PrithvaTopazOreBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.STONE).strength(4f, 15f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.prithva_topaz_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VajradaAmethystBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vajrada/VajradaAmethystBlock.java", "snippet": "public class VajradaAmethystBlock extends Block {\n public VajradaAmethystBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 11f));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VajradaAmethystOre", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vajrada/VajradaAmethystOre.java", "snippet": "public class VajradaAmethystOre extends Block {\n public VajradaAmethystOre() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.STONE).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vajrada_amethyst_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VayudaTurquoiseGemstoneBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vayuda/VayudaTurquoiseGemstoneBlock.java", "snippet": "public class VayudaTurquoiseGemstoneBlock extends Block {\n public VayudaTurquoiseGemstoneBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vayuda_turquoise_gemstone_block.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VayudaTurquoiseGemstoneOre", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vayuda/VayudaTurquoiseGemstoneOre.java", "snippet": "public class VayudaTurquoiseGemstoneOre extends Block {\n public VayudaTurquoiseGemstoneOre() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vayuda_turquoise_gemstone_ore.line1\"));\n }\n\n @Override\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() == this || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/com/primogemstudio/primogemcraft/PrimogemCraftFabric.java", "snippet": "public static final String MOD_ID = \"primogemcraft\";" } ]
import com.primogemstudio.primogemcraft.blocks.instances.*; import com.primogemstudio.primogemcraft.blocks.instances.dendrocore.*; import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystOre; import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneOre; import com.primogemstudio.primogemcraft.blocks.instances.mora.*; import com.primogemstudio.primogemcraft.blocks.instances.planks.*; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID;
4,392
package com.primogemstudio.primogemcraft.blocks; public class PrimogemCraftBlocks { public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock()); public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock()); public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre()); public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops())); public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock()); public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock()); public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock()); public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock()); public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock()); public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock()); public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock()); public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock()); public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock()); public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock()); public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock()); public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock()); public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock()); public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock()); public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock()); public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock()); public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock()); public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock()); public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock()); public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre()); public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock()); public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre());
package com.primogemstudio.primogemcraft.blocks; public class PrimogemCraftBlocks { public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock()); public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock()); public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre()); public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops())); public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock()); public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock()); public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock()); public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock()); public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock()); public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock()); public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock()); public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock()); public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock()); public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock()); public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock()); public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock()); public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock()); public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock()); public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock()); public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock()); public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock()); public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock()); public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock()); public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre()); public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock()); public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre());
public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock());
6
2023-10-15 08:07:06+00:00
8k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/formats/MovesTable.java
[ { "identifier": "CellTypes", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/CellTypes.java", "snippet": "public enum CellTypes\n{\n INTEGER,\n STRING,\n COMBO_BOX,\n COLORED_COMBO_BOX,\n BITFIELD_COMBO_BOX,\n CHECKBOX,\n CUSTOM;\n\n\n public interface CustomCellFunctionSupplier {\n\n TableCellEditor getEditor(String[]... strings);\n TableCellRenderer getRenderer(String[]... strings);\n }\n}" }, { "identifier": "DefaultTable", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/DefaultTable.java", "snippet": "public abstract class DefaultTable<G extends GenericFileData, E extends Enum<E>> extends JTable\n{\n final CellTypes[] cellTypes;\n private final int[] widths;\n private final List<TextBankData> textData;\n\n private final FormatModel<G, E> formatModel;\n\n private final CellTypes.CustomCellFunctionSupplier customCellSupplier;\n\n public DefaultTable(FormatModel<G, E> model, List<TextBankData> textData, int[] widths, CellTypes.CustomCellFunctionSupplier customCellSupplier)\n {\n super(model);\n this.formatModel = model;\n\n cellTypes = new CellTypes[getColumnCount()];\n for (int i = 0; i < cellTypes.length; i++)\n {\n cellTypes[i] = model.getCellType(i);\n }\n// cellTypes = Arrays.copyOfRange(cellTypes, getNumFrozenColumns(), cellTypes.length);\n widths = Arrays.copyOfRange(widths, model.getNumFrozenColumns(), widths.length);\n\n// this.cellTypes = cellTypes;\n this.widths = widths;\n this.textData = textData;\n this.customCellSupplier = customCellSupplier;\n setAutoResizeMode(JTable.AUTO_RESIZE_OFF);\n\n setRowMargin(1);\n getColumnModel().setColumnMargin(1);\n setShowGrid(true);\n setGridColor(Color.black);\n setShowHorizontalLines(true);\n setShowVerticalLines(true);\n\n// setBackground(Color.WHITE);\n// setForeground(Color.black);\n\n loadCellRenderers(obtainTextSources(textData));\n\n MultiLineTableHeaderRenderer renderer = new MultiLineTableHeaderRenderer();\n Enumeration<TableColumn> columns = getColumnModel().getColumns();\n while (columns.hasMoreElements())\n {\n columns.nextElement().setHeaderRenderer(renderer);\n }\n\n setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);\n getTableHeader().setReorderingAllowed(false);\n setDragEnabled(false);\n\n setRowSelectionAllowed(true);\n setColumnSelectionAllowed(true);\n setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);\n\n InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);\n\n PasteAction action = new PasteAction(this);\n\n KeyStroke stroke;\n if (!SystemInfo.isMacOS) {\n stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false);\n } else {\n stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.META_MASK, false);\n }\n\n inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PASTE, 0), action);\n registerKeyboardAction(action, \"Paste\", stroke, JComponent.WHEN_FOCUSED);\n// inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction()\n// {\n// @Override\n// public void actionPerformed(ActionEvent e)\n// {\n// System.out.println(\"moo\");\n// editingCanceled(null);\n// }\n// });\n\n// inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), \"cancel\");\n\n// addKeyListener(new KeyAdapter()\n// {\n// @Override\n// public void keyPressed(KeyEvent e)\n// {\n//// super.keyPressed(e);\n// if (e.getKeyCode() == KeyEvent.VK_ESCAPE)\n// clearSelection();\n// }\n// });\n setDefaultRenderer(Object.class, new DefaultSheetCellRenderer());\n }\n\n public abstract Queue<String[]> obtainTextSources(List<TextBankData> textData);\n\n public FormatModel<G, E> getFormatModel()\n {\n return formatModel;\n }\n\n public abstract Class<G> getDataClass();\n\n// public abstract int getNumFrozenColumns();\n\n public void loadCellRenderers(Queue<String[]> textSources)\n {\n TableCellEditor customEditor = null;\n TableCellRenderer customRenderer = null;\n\n for (int i = 0; i < getColumnCount(); i++)\n {\n CellTypes c = cellTypes[i];\n TableColumn col = getColumnModel().getColumn(i);\n col.setWidth(widths[i]);\n col.setPreferredWidth(widths[i]);\n\n if (c == CellTypes.CHECKBOX)\n {\n col.setCellRenderer(new CheckBoxRenderer());\n col.setCellEditor(new CheckBoxEditor());\n }\n else if (c == CellTypes.COMBO_BOX || c == CellTypes.COLORED_COMBO_BOX || c == CellTypes.BITFIELD_COMBO_BOX)\n {\n String[] text = getTextFromSource(textSources);\n\n if (c != CellTypes.BITFIELD_COMBO_BOX) //normal and colored\n col.setCellEditor(new ComboBoxCellEditor(text));\n else // bitfield combo box\n col.setCellEditor(new BitfieldComboBoxEditor(text));\n\n if (c == CellTypes.COMBO_BOX)\n col.setCellRenderer(new IndexedStringCellRenderer(text));\n else if (c == CellTypes.COLORED_COMBO_BOX)\n col.setCellRenderer(new IndexedStringCellRenderer.ColoredIndexedStringCellRenderer(text, PokeditorManager.typeColors));\n else\n col.setCellRenderer(new BitfieldStringCellRenderer(text));\n }\n else if (c == CellTypes.INTEGER)\n {\n col.setCellEditor(new NumberOnlyCellEditor());\n }\n else if (c == CellTypes.CUSTOM)\n {\n if (customEditor == null || customRenderer == null)\n {\n String[] speciesNames = getTextFromSource(textSources);\n String[] itemNames = getTextFromSource(textSources);\n String[] moveNames = getTextFromSource(textSources);\n\n customEditor = customCellSupplier.getEditor(speciesNames, itemNames, moveNames);\n customRenderer = customCellSupplier.getRenderer(speciesNames, itemNames, moveNames);\n }\n\n if (customEditor != null)\n col.setCellEditor(customEditor);\n\n if (customRenderer != null)\n col.setCellRenderer(customRenderer);\n }\n }\n }\n\n private String[] getTextFromSource(Queue<String[]> textSources)\n {\n String[] text = textSources.remove();\n if (text == null)\n text = new String[] {\"\"};\n\n return text;\n }\n\n public void resetIndexedCellRendererText()\n {\n Queue<String[]> textSources = obtainTextSources(textData);\n for (int i = 0; i < getColumnCount(); i++)\n {\n CellTypes c = cellTypes[i];\n TableColumn col = getColumnModel().getColumn(i);\n\n if (c == CellTypes.COMBO_BOX || c == CellTypes.COLORED_COMBO_BOX || c == CellTypes.BITFIELD_COMBO_BOX)\n {\n String[] text = textSources.remove();\n if (text == null)\n text = new String[] {\"\"};\n ((ComboBoxCellEditor) col.getCellEditor()).setItems(text);\n ((IndexedStringCellRenderer) col.getCellRenderer()).setItems(text);\n }\n }\n }\n\n public String[][] exportClean()\n {\n String[][] output = new String[getModel().getRowCount()][getColumnCount()];\n for (int colIdx = 0; colIdx < output[0].length; colIdx++)\n {\n TableColumn column = getColumnModel().getColumn(colIdx);\n TableCellRenderer renderer = column.getCellRenderer();\n if (renderer != null && !(renderer instanceof CheckBoxRenderer))\n {\n for (int rowIdx = 0; rowIdx < output.length; rowIdx++)\n {\n output[rowIdx][colIdx] = ((DefaultTableCellRenderer) prepareRenderer(renderer, rowIdx, colIdx)).getText();\n }\n }\n else\n {\n for (int rowIdx = 0; rowIdx < output.length; rowIdx++)\n {\n output[rowIdx][colIdx] = String.valueOf(getValueAt(rowIdx, colIdx));\n }\n }\n\n }\n\n return output;\n }\n\n public String[][] exportEditable()\n {\n String[][] output = new String[getModel().getRowCount()][getColumnCount()];\n for (int colIdx = 0; colIdx < output[0].length; colIdx++)\n {\n for (int rowIdx = 0; rowIdx < output.length; rowIdx++)\n {\n output[rowIdx][colIdx] = String.valueOf(getValueAt(rowIdx, colIdx));\n }\n }\n\n return output;\n }\n\n public static String[] loadStringsFromKeys(String... keys)\n {\n ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);\n String[] result = new String[keys.length];\n int idx = 0;\n for (String s : keys) {\n result[idx++] = bundle.getString(s);\n }\n return result;\n }\n\n public static class PasteAction extends AbstractAction {\n\n private final DefaultTable<? extends GenericFileData, ? extends Enum<?>> table;\n\n public PasteAction(DefaultTable<? extends GenericFileData, ? extends Enum<?>> table)\n {\n this.table = table;\n }\n\n @Override\n public void actionPerformed(ActionEvent e)\n {\n int[] rows = table.getSelectedRows();\n System.out.println(\"rows: \" + Arrays.toString(rows));\n int[] cols = table.getSelectedColumns();\n\n Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();\n if (cb.isDataFlavorAvailable(DataFlavor.stringFlavor))\n {\n try\n {\n String value = (String) cb.getData(DataFlavor.stringFlavor);\n String[] lines = value.split(\"\\n\");\n String[][] pastedCells = new String[lines.length][];\n int idx = 0;\n for (String line : lines) {\n pastedCells[idx++] = line.split(\"\\t\");\n }\n\n int numVerticalCopies = (int) Math.round(((double) rows.length) / pastedCells.length);\n int numHorizontalCopies = (int) Math.round(((double) cols.length) / pastedCells[0].length);\n\n for (int verticalCopyIdx = 0; verticalCopyIdx < numVerticalCopies; verticalCopyIdx++)\n {\n for (int horizontalCopyIdx = 0; horizontalCopyIdx < numHorizontalCopies; horizontalCopyIdx++)\n {\n for (int rowIdx = 0; rowIdx < pastedCells.length; rowIdx++)\n {\n for (int colIdx = 0; colIdx < pastedCells[0].length; colIdx++)\n {\n int destRow = rows[0] + verticalCopyIdx * pastedCells.length + rowIdx;\n int destCol = cols[0] + horizontalCopyIdx * pastedCells[0].length + colIdx;\n\n// System.out.println(\"Setting value at (\" + destRow + \",\" + destCol + \") to: \" + pastedCells[rowIdx][colIdx]);\n table.setValueAt(pastedCells[rowIdx][colIdx], destRow, destCol);\n table.getFormatModel().fireTableCellUpdated(destRow, destCol);\n }\n }\n }\n }\n\n// for (int userSelectedRow : rows)\n// {\n// for (int rowIdx = 0; rowIdx < pastedCells.length; rowIdx++)\n// {\n// for (int colIdx = 0; colIdx < pastedCells[0].length; colIdx++)\n// {\n// table.setValueAt(pastedCells[rowIdx][colIdx], userSelectedRow + rowIdx, cols[0] + colIdx);\n// table.getFormatModel().fireTableCellUpdated(userSelectedRow + rowIdx, cols[0] + colIdx);\n// }\n// }\n// }\n\n// table.setValueAt(value, row, col);\n }\n catch (UnsupportedFlavorException | IOException ex)\n {\n ex.printStackTrace();\n }\n }\n }\n }\n}" }, { "identifier": "FormatModel", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/FormatModel.java", "snippet": "public abstract class FormatModel<G extends GenericFileData, E extends Enum<E>> extends AbstractTableModel implements EditorDataModel<E>\n{\n private final List<G> data;\n private final List<TextBankData> textBankData;\n private final String[] columnNames;\n\n private boolean copyPasteModeEnabled;\n\n public FormatModel(List<G> data, List<TextBankData> textBankData)\n {\n this.data = data;\n this.textBankData = textBankData;\n this.columnNames = new String[getColumnCount() + getNumFrozenColumns()];\n\n ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);\n\n int lastValid = 0;\n for (int idx = 0; idx < columnNames.length; idx++)\n {\n int adjusted = idx-getNumFrozenColumns();\n String columnNameKey = getColumnNameKey(adjusted);\n if (columnNameKey == null)\n {\n columnNames[idx] = bundle.getString(getColumnNameKey(adjusted % (lastValid + 1))); // this will cause columns to repeat as much as needed for the sheets which need them\n }\n else {\n columnNames[idx] = bundle.getString(columnNameKey);\n lastValid = adjusted;\n }\n\n }\n\n copyPasteModeEnabled = false;\n }\n\n public int getNumFrozenColumns() {\n return 0;\n }\n\n public abstract String getColumnNameKey(int columnIndex);\n\n @Override\n public String getColumnName(int column)\n {\n return columnNames[column + getNumFrozenColumns()];\n }\n\n public void toggleCopyPasteMode(boolean state)\n {\n copyPasteModeEnabled = state;\n }\n\n @Override\n public boolean isCellEditable(int rowIndex, int columnIndex)\n {\n return !copyPasteModeEnabled;\n }\n\n @Override\n public int getRowCount()\n {\n return getEntryCount();\n }\n\n @Override\n public int getEntryCount()\n {\n return data.size();\n }\n\n @Override\n public String getEntryName(int entryIdx)\n {\n return \"\" + entryIdx;\n }\n\n public List<G> getData()\n {\n return data;\n }\n\n public List<TextBankData> getTextBankData()\n {\n return textBankData;\n }\n\n protected CellTypes getCellType(int columnIndex)\n {\n return CellTypes.STRING;\n }\n\n public abstract FormatModel<G, E> getFrozenColumnModel();\n\n public Object prepareObjectForWriting(Object aValue, CellTypes cellType)\n {\n if (aValue instanceof String)\n {\n if (cellType == CellTypes.CHECKBOX)\n aValue = Boolean.parseBoolean(((String) aValue).trim());\n else if (cellType != CellTypes.STRING)\n aValue = Integer.parseInt(((String) aValue).trim());\n }\n return aValue;\n }\n}" } ]
import io.github.turtleisaac.pokeditor.formats.moves.MoveData; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gamedata.TextFiles; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes; import io.github.turtleisaac.pokeditor.gui.sheets.tables.DefaultTable; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import java.util.LinkedList; import java.util.List; import java.util.Queue;
4,229
package io.github.turtleisaac.pokeditor.gui.sheets.tables.formats; public class MovesTable extends DefaultTable<MoveData, MovesTable.MovesColumn> { public static final int[] columnWidths = new int[] {40, 100, 500, 100, 65, 100, 65, 65, 120, 160, 65, 65, 80, 80, 80, 80, 80, 80, 80, 80, 65, 65}; private static final String[] categoryKeys = new String[] {"category.physical", "category.special", "category.status"}; private static final String[] targetKeys = new String[] {"target.selected", "target.automatic", "target.random", "target.bothFoes", "target.allExceptUser", "target.user", "target.userSide", "target.entireField", "target.foeSide", "target.ally", "target.userOrAlly", "target.MOVE_TARGET_ME_FIRST"}; public MovesTable(List<MoveData> data, List<TextBankData> textData) { super(new MovesModel(data, textData), textData, columnWidths, null); } @Override public Queue<String[]> obtainTextSources(List<TextBankData> textData) { Queue<String[]> textSources = new LinkedList<>(); String[] categories = DefaultTable.loadStringsFromKeys(categoryKeys); String[] typeNames = textData.get(TextFiles.TYPE_NAMES.getValue()).getStringList().toArray(String[]::new); String[] targets = DefaultTable.loadStringsFromKeys(targetKeys); // String[] arr = new String[500]; // Arrays.fill(arr, "Moo"); textSources.add(categories); textSources.add(typeNames); textSources.add(targets); // textSources.add(arr); return textSources; } @Override public Class<MoveData> getDataClass() { return MoveData.class; }
package io.github.turtleisaac.pokeditor.gui.sheets.tables.formats; public class MovesTable extends DefaultTable<MoveData, MovesTable.MovesColumn> { public static final int[] columnWidths = new int[] {40, 100, 500, 100, 65, 100, 65, 65, 120, 160, 65, 65, 80, 80, 80, 80, 80, 80, 80, 80, 65, 65}; private static final String[] categoryKeys = new String[] {"category.physical", "category.special", "category.status"}; private static final String[] targetKeys = new String[] {"target.selected", "target.automatic", "target.random", "target.bothFoes", "target.allExceptUser", "target.user", "target.userSide", "target.entireField", "target.foeSide", "target.ally", "target.userOrAlly", "target.MOVE_TARGET_ME_FIRST"}; public MovesTable(List<MoveData> data, List<TextBankData> textData) { super(new MovesModel(data, textData), textData, columnWidths, null); } @Override public Queue<String[]> obtainTextSources(List<TextBankData> textData) { Queue<String[]> textSources = new LinkedList<>(); String[] categories = DefaultTable.loadStringsFromKeys(categoryKeys); String[] typeNames = textData.get(TextFiles.TYPE_NAMES.getValue()).getStringList().toArray(String[]::new); String[] targets = DefaultTable.loadStringsFromKeys(targetKeys); // String[] arr = new String[500]; // Arrays.fill(arr, "Moo"); textSources.add(categories); textSources.add(typeNames); textSources.add(targets); // textSources.add(arr); return textSources; } @Override public Class<MoveData> getDataClass() { return MoveData.class; }
static class MovesModel extends FormatModel<MoveData, MovesColumn>
2
2023-10-15 05:00:57+00:00
8k
xiezhihui98/GAT1400
src/main/java/com/cz/viid/framework/service/impl/VIIDSubscribeServiceImpl.java
[ { "identifier": "Constants", "path": "src/main/java/com/cz/viid/framework/config/Constants.java", "snippet": "public class Constants {\n public static class KAFKA_CONSUMER {\n public static final String APP_DEFAULT_GROUP = \"GA1400_BACKEND\";\n\n //消费失败重试topic\n public static final String FACE_INFO_RETRY_TOPIC = APP_DEFAULT_GROUP + \"_FACE_INFO_RETRY\";\n public static final String MOTOR_VEHICLE_RETRY_TOPIC = APP_DEFAULT_GROUP + \"_MOTOR_VEHICLE_RETRY\";\n }\n\n public static class DEFAULT_TOPIC_PREFIX {\n //卡口设备前缀\n public static final String TOLLGATE_DEVICE = \"GA1400-TOLLGATE_DEVICE-\";\n //车辆抓拍前缀\n public static final String MOTOR_VEHICLE = \"GA1400-MOTOR_VEHICLE-\";\n //采集设备前缀\n public static final String APE_DEVICE = \"GA1400-APE_DEVICE-\";\n //人脸抓拍前缀\n public static final String FACE_RECORD = \"GA1400-FACE_RECORD-\";\n //非机动车前缀\n public static final String NON_MOTOR_VEHICLE = \"GA1400-NON_MOTOR_VEHICLE-\";\n //人员抓拍前缀\n public static final String PERSON_RECORD = \"GA1400-PERSON_RECORD-\";\n\n public static final String RAW = \"GA1400-RAW-\";\n }\n\n public static class VIID_SERVER {\n public static class TRANSMISSION {\n public static final String HTTP = \"http\";\n public static final String WEBSOCKET = \"websocket\";\n }\n public static class SERVER_CATEGORY {\n //自己\n public static final String GATEWAY = \"0\";\n //下级\n public static final String DOWN_DOMAIN = \"1\";\n public static final String UP_DOMAIN = \"2\";\n }\n public static class RESOURCE_CLASS {\n //卡口ID\n public static final Integer TOLLGATE = 0;\n //视图库ID\n public static final Integer VIEW_LIBRARY = 4;\n }\n\n public static class SUBSCRIBE_DETAIL {\n //案(事)件目录\n public static final String AN_JIANG_DIR = \"1\";\n //单个案(事)件目录\n public static final String AN_JIANG = \"2\";\n //采集设备目录\n public static final String DEVICE_DIR = \"3\";\n //采集设备状态\n public static final String DEVICE_STATUS = \"4\";\n //采集系统目录\n public static final String SYSTEM_DIR = \"5\";\n //采集系统状态\n public static final String SYSTEM_STATUS = \"6\";\n //视频卡口目录\n public static final String VIDEO_TOLLGATE_DIR = \"7\";\n //单个卡口记录\n public static final String TOLLGATE_RECORD = \"8\";\n //车道目录\n public static final String CHE_DAO_DIR = \"9\";\n //单个车道记录\n public static final String CHE_DAO = \"10\";\n //自动采集的人员信息\n public static final String PERSON_INFO = \"11\";\n //自动采集的人脸信息\n public static final String FACE_INFO = \"12\";\n //自动采集的车辆信息\n public static final String PLATE_INFO = \"13\";\n //自动采集的非机动车辆信息\n public static final String PLATE_MIRCO_INFO = \"14\";\n //自动采集的物品信息\n public static final String SUBSTANCE_INFO = \"15\";\n //自动采集的文件信息\n public static final String FILE_INFO = \"16\";\n\n public static final String RAW = \"999\";\n }\n }\n\n public static class SUBSCRIBE {\n public static class OPERATE_TYPE {\n public static final Integer CONTINUE = 0;\n public static final Integer CANCEL = 1;\n }\n\n public static class STATUS {\n public static final Integer CONTINUE = 0;\n public static final Integer CANCEL = 1;\n public static final Integer EXPIRE = 2;\n public static final Integer INACTIVE = 9;\n }\n }\n}" }, { "identifier": "RedisConfig", "path": "src/main/java/com/cz/viid/framework/config/RedisConfig.java", "snippet": "@EnableCaching\n@Configuration\npublic class RedisConfig {\n\n public static final String CACHE_10MIN = \"CACHE_10MIN\";\n public static final String CACHE_15MIN = \"CACHE_15MIN\";\n public static final String CACHE_30MIN = \"CACHE_30MIN\";\n public static final String CACHE_1HOUSE = \"CACHE_1HOUSE\";\n public static final String CACHE_1DAY = \"CACHE_1DAY\";\n\n @Resource\n ObjectMapper objectMapper;\n\n @Bean\n public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {\n RedisTemplate<String, Object> template = new RedisTemplate<>();\n template.setConnectionFactory(redisConnectionFactory);\n StringRedisSerializer serializer = new StringRedisSerializer();\n Jackson2JsonRedisSerializer<Object> jackson = new Jackson2JsonRedisSerializer<>(Object.class);\n template.setValueSerializer(jackson);\n template.setHashValueSerializer(jackson);\n template.setKeySerializer(serializer);\n template.setHashKeySerializer(serializer);\n return template;\n }\n\n @Bean\n public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {\n StringRedisSerializer serializer = new StringRedisSerializer();\n Jackson2JsonRedisSerializer<Object> jackson = new Jackson2JsonRedisSerializer<>(Object.class);\n\n ObjectMapper copyMapper = objectMapper.copy();\n copyMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);\n copyMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);\n copyMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);\n copyMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);\n jackson.setObjectMapper(copyMapper);\n\n Map<String, Duration> cacheMap = new HashMap<>();\n cacheMap.put(CACHE_10MIN, Duration.ofMinutes(10));\n cacheMap.put(CACHE_15MIN, Duration.ofMinutes(15));\n cacheMap.put(CACHE_30MIN, Duration.ofMinutes(30));\n cacheMap.put(CACHE_1HOUSE, Duration.ofHours(1));\n cacheMap.put(CACHE_1DAY, Duration.ofDays(1));\n return builder -> {\n for (Map.Entry<String, Duration> entry : cacheMap.entrySet()) {\n builder.withCacheConfiguration(entry.getKey(),\n RedisCacheConfiguration.defaultCacheConfig()\n .entryTtl(entry.getValue())\n .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))\n .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson))\n .disableCachingNullValues()\n\n );\n }\n };\n }\n\n}" }, { "identifier": "ResponseStatusObject", "path": "src/main/java/com/cz/viid/framework/domain/dto/ResponseStatusObject.java", "snippet": "@Data\npublic class ResponseStatusObject {\n\n @JsonProperty(\"Id\")\n private String id;\n @JsonProperty(\"RequestURL\")\n private String requestUrl;\n @JsonProperty(\"StatusCode\")\n private String statusCode;\n @JsonProperty(\"StatusString\")\n private String statusString;\n @JsonProperty(\"LocalTime\")\n private String localTime;\n\n public ResponseStatusObject() {\n }\n\n public ResponseStatusObject(String requestUrl, String statusCode, String statusString) {\n this(null, requestUrl, statusCode, statusString);\n }\n\n public ResponseStatusObject(String id, String requestUrl, String statusCode, String statusString) {\n this.id = id;\n this.requestUrl = requestUrl;\n this.statusCode = statusCode;\n this.statusString = statusString;\n this.localTime = DateFormatUtils.format(new Date(), \"yyyyMMddHHmmss\");\n }\n\n}" }, { "identifier": "SubscribeObject", "path": "src/main/java/com/cz/viid/framework/domain/dto/SubscribeObject.java", "snippet": "@Data\n@EqualsAndHashCode\n@ToString\npublic class SubscribeObject {\n\n @ApiModelProperty(\"订阅标识符\")\n @JsonProperty(\"SubscribeID\")\n private String subscribeId;\n @ApiModelProperty(\"订阅标题\")\n @JsonProperty(\"Title\")\n private String title;\n @ApiModelProperty(value = \"订阅类型\", notes = \"\")\n @JsonProperty(\"SubscribeDetail\")\n private String subscribeDetail;\n @ApiModelProperty(\"资源ID(卡口ID)\")\n @JsonProperty(\"ResourceURI\")\n private String resourceUri;\n @ApiModelProperty(\"申请人\")\n @JsonProperty(\"ApplicantName\")\n @TableField(\"application_name\")\n private String applicationName;\n @ApiModelProperty(\"申请单位\")\n @JsonProperty(\"ApplicantOrg\")\n private String applicationOrg;\n @ApiModelProperty(\"开始时间\")\n @JsonProperty(\"BeginTime\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n private Date beginTime;\n @ApiModelProperty(\"结束时间\")\n @JsonProperty(\"EndTime\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n private Date endTime;\n @ApiModelProperty(\"订阅回调地址\")\n @JsonProperty(\"ReceiveAddr\")\n private String receiveAddr;\n @ApiModelProperty(\"数据上报间隔\")\n @JsonProperty(\"ReportInterval\")\n private Integer reportInterval;\n @ApiModelProperty(\"理由\")\n @JsonProperty(\"Reason\")\n private String reason;\n @ApiModelProperty(value = \"操作类型\", notes = \"0=订阅,1=取消订阅\")\n @JsonProperty(\"OperateType\")\n private Integer operateType;\n @ApiModelProperty(value = \"订阅状态\", notes = \"0=订阅中,1=已取消订阅,2=订阅到期,9=未订阅\")\n @JsonProperty(\"SubscribeStatus\")\n private Integer subscribeStatus;\n @JsonProperty(\"ResourceClass\")\n private Integer resourceClass;\n @JsonIgnore\n @JsonProperty(\"ResultImageDeclare\")\n private String resultImageDeclare;\n @JsonIgnore\n @JsonProperty(\"ResultFeatureDeclare\")\n private Integer resultFeatureDeclare;\n}" }, { "identifier": "VIIDServer", "path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDServer.java", "snippet": "@Data\n@TableName(\"viid_server\")\npublic class VIIDServer {\n\n @ApiModelProperty(value = \"视图库编号\")\n @TableId(value = \"server_id\",type = IdType.NONE)\n private String serverId;\n @ApiModelProperty(value = \"视图库名称\")\n @TableField(value = \"server_name\")\n private String serverName;\n @ApiModelProperty(value = \"交互协议\")\n @TableField(\"scheme\")\n private String scheme = \"http\";\n @ApiModelProperty(value = \"视图库地址\")\n @TableField(value = \"host\")\n private String host;\n @ApiModelProperty(value = \"视图库端口\")\n @TableField(value = \"port\")\n private Integer port;\n @ApiModelProperty(value = \"授权用户\")\n @TableField(value = \"username\")\n private String username;\n @ApiModelProperty(value = \"授权用户凭证\")\n @TableField(value = \"authenticate\")\n private String authenticate;\n @ApiModelProperty(value = \"是否启用\")\n @TableField(value = \"enabled\")\n private Boolean enabled;\n @ApiModelProperty(value = \"服务类别\", notes = \"0=自己,1=下级,2=上级\")\n @TableField(value = \"category\")\n private String category;\n @ApiModelProperty(\"创建时间\")\n @TableField(value = \"create_time\")\n private Date createTime;\n @ApiModelProperty(\"是否开启双向保活\")\n @TableField(value = \"keepalive\")\n private Boolean keepalive;\n @ApiModelProperty(value = \"数据传输类型\", example = \"HTTP\")\n @TableField(\"transmission\")\n private String transmission = Constants.VIID_SERVER.TRANSMISSION.HTTP;\n @ApiModelProperty(\"在线状态\")\n @TableField(value = \"online\", exist = false)\n private Boolean online = false;\n\n public String httpUrlBuilder() {\n return scheme + \"://\" + host + \":\" + port;\n }\n}" }, { "identifier": "VIIDSubscribe", "path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDSubscribe.java", "snippet": "@Data\n@EqualsAndHashCode\n@ToString\n@TableName(value = \"viid_subscrube\", autoResultMap = true)\npublic class VIIDSubscribe {\n\n @ApiModelProperty(\"订阅标识符\")\n @TableId(value = \"subscribe_id\", type = IdType.NONE)\n private String subscribeId;\n @ApiModelProperty(\"订阅标题\")\n @TableField(\"title\")\n private String title;\n @ApiModelProperty(\"订阅类型,7=视频卡口设备,13=车辆信息(卡口过车记录)\")\n @TableField(\"subscribe_detail\")\n private String subscribeDetail;\n @ApiModelProperty(\"资源ID(卡口ID)\")\n @TableField(value = \"resource_uri\", typeHandler = StringToArrayTypeHandler.class, jdbcType = JdbcType.ARRAY)\n private String resourceUri;\n @ApiModelProperty(\"申请人\")\n @TableField(\"application_name\")\n private String applicationName;\n @ApiModelProperty(\"申请单位\")\n @TableField(\"application_org\")\n private String applicationOrg;\n @ApiModelProperty(\"开始时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"begin_time\")\n private Date beginTime;\n @ApiModelProperty(\"结束时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"end_time\")\n private Date endTime;\n @ApiModelProperty(\"订阅回调地址\")\n @TableField(\"receive_addr\")\n private String receiveAddr;\n @ApiModelProperty(\"数据上报间隔\")\n @TableField(\"report_interval\")\n private Integer reportInterval;\n @ApiModelProperty(\"理由\")\n @TableField(\"reason\")\n private String reason;\n @ApiModelProperty(\"操作类型(0=订阅,1=取消订阅)\")\n @TableField(\"operate_type\")\n private Integer operateType;\n @ApiModelProperty(\"订阅状态(0=订阅中,1=已取消订阅,2=订阅到期,9=未订阅)\")\n @TableField(\"subscribe_status\")\n private Integer subscribeStatus;\n @TableField(\"resource_class\")\n private Integer resourceClass;\n @JsonIgnore\n @TableField(\"result_image_declare\")\n private String resultImageDeclare;\n @JsonIgnore\n @TableField(\"result_feature_declare\")\n private Integer resultFeatureDeclare;\n @TableField(\"server_id\")\n private String serverId;\n @TableField(\"create_time\")\n private Date createTime = new Date();\n}" }, { "identifier": "SubscribesRequest", "path": "src/main/java/com/cz/viid/framework/domain/vo/SubscribesRequest.java", "snippet": "@Data\npublic class SubscribesRequest {\n\n @JsonProperty(\"SubscribeListObject\")\n private SubscribeListObject subscribeListObject;\n\n public static SubscribesRequest create(List<SubscribeObject> subscribes) {\n SubscribesRequest request = new SubscribesRequest();\n SubscribeListObject subscribeListObject = new SubscribeListObject();\n subscribeListObject.setSubscribeObject(subscribes);\n request.setSubscribeListObject(subscribeListObject);\n return request;\n }\n\n public static SubscribesRequest create(SubscribeObject subscribes) {\n SubscribesRequest request = new SubscribesRequest();\n SubscribeListObject subscribeListObject = new SubscribeListObject();\n subscribeListObject.setSubscribeObject(Collections.singletonList(subscribes));\n request.setSubscribeListObject(subscribeListObject);\n return request;\n }\n}" }, { "identifier": "VIIDSubscribesResponse", "path": "src/main/java/com/cz/viid/framework/domain/vo/VIIDSubscribesResponse.java", "snippet": "@Data\npublic class VIIDSubscribesResponse {\n\n @JsonProperty(\"ResponseStatusListObject\")\n private ResponseStatusListObject responseStatusListObject;\n\n public static VIIDSubscribesResponse create(List<ResponseStatusObject> responseStatusObject) {\n ResponseStatusListObject responseStatusListObject = new ResponseStatusListObject();\n responseStatusListObject.setResponseStatusObject(responseStatusObject);\n return create(responseStatusListObject);\n }\n\n public static VIIDSubscribesResponse create(ResponseStatusListObject responseStatusListObject) {\n VIIDSubscribesResponse response = new VIIDSubscribesResponse();\n response.setResponseStatusListObject(responseStatusListObject);\n return response;\n }\n}" }, { "identifier": "VIIDSubscribeMapper", "path": "src/main/java/com/cz/viid/framework/mapper/VIIDSubscribeMapper.java", "snippet": "@Mapper\npublic interface VIIDSubscribeMapper extends BaseMapper<VIIDSubscribe> {\n}" }, { "identifier": "VIIDServerService", "path": "src/main/java/com/cz/viid/framework/service/VIIDServerService.java", "snippet": "public interface VIIDServerService extends IService<VIIDServer> {\n\n void afterPropertiesSet();\n VIIDServer getByIdAndEnabled(String id);\n\n VIIDServer getCurrentServer(boolean useCache);\n VIIDServer getCurrentServer();\n\n VIIDServer register(RegisterRequest request, DigestData digestData);\n\n boolean unRegister(String deviceId);\n\n ResponseStatusObject keepalive(String deviceId);\n\n Page<VIIDServer> list(SearchDataRequest request);\n\n boolean upsert(VIIDServer request);\n\n void changeDomain(String source);\n\n boolean maintenance(VIIDServer viidServer);\n}" }, { "identifier": "VIIDSubscribeService", "path": "src/main/java/com/cz/viid/framework/service/VIIDSubscribeService.java", "snippet": "public interface VIIDSubscribeService extends IService<VIIDSubscribe> {\n\n VIIDSubscribe getCacheById(String subscribeId);\n\n VIIDSubscribesResponse subscribes(VIIDSubscribeRequest request);\n\n VIIDSubscribesResponse unSubscribes(VIIDSubscribeRequest request);\n\n Page<VIIDSubscribe> list(VIIDSubscribeRequest request);\n}" }, { "identifier": "VIIDServerClient", "path": "src/main/java/com/cz/viid/rpc/VIIDServerClient.java", "snippet": "@FeignClient(name = \"VIIDServerClient\", url = \"http://127.0.0.254\")\npublic interface VIIDServerClient {\n\n @PostMapping(\"/VIID/System/Register\")\n Response register(URI uri, @RequestBody RegisterRequest request,\n @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization);\n\n @PostMapping(\"/VIID/System/UnRegister\")\n VIIDBaseResponse unRegister(URI uri, @RequestBody UnRegisterRequest request,\n @RequestHeader(\"User-Identify\") String authorization);\n\n @PostMapping(\"/VIID/System/Keepalive\")\n VIIDBaseResponse keepalive(URI uri, @RequestBody KeepaliveRequest keepaliveRequest,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PostMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse addSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PutMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse updateSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @DeleteMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse cancelSubscribes(URI uri, @RequestParam(\"IDList\") List<String> resourceIds,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n// @PostMapping(\"/VIID/SubscribeNotifications\")\n @PostMapping\n VIIDNotificationResponse subscribeNotifications(URI uri, @RequestBody SubscribeNotificationRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n}" }, { "identifier": "StructCodec", "path": "src/main/java/com/cz/viid/utils/StructCodec.java", "snippet": "public class StructCodec {\n\n /**\n * 卡口订阅构建\n * 备注: SubscribeDetail 有时候无法订阅单个资源, 可以多加一个,标识多个资源 例: \"7,\"\n * @param resourceUri 卡口ID, 多个ID使用,分隔\n * @param title 订阅标题\n * @param server 服务节点\n * @param subscribeDetail 订阅资源类型 7=视频卡口目录(卡口设备) 13=车辆数据(卡口过车)\n * @return 订阅对象\n */\n public static SubscribeObject inputSubscribeBuilder(String resourceUri, String title,\n String subscribeDetail, VIIDServer server) {\n SubscribeObject subscribe = new SubscribeObject();\n subscribe.setSubscribeId(randomSubscriberId(server.getServerId()));\n subscribe.setTitle(title);\n if (Constants.VIID_SERVER.SUBSCRIBE_DETAIL.VIDEO_TOLLGATE_DIR.equals(subscribeDetail)\n || Constants.VIID_SERVER.SUBSCRIBE_DETAIL.DEVICE_DIR.equals(subscribeDetail)) {\n //TODO 防止低版本海口平台bug\n subscribe.setSubscribeDetail(subscribeDetail + \",\");\n } else {\n subscribe.setSubscribeDetail(subscribeDetail);\n }\n subscribe.setResourceUri(resourceUri);\n subscribe.setApplicationName(\"bdmap_yt\");\n subscribe.setApplicationOrg(\"d1\");\n subscribe.setBeginTime(DateUtils.addHours(new Date(), -8));\n try {\n subscribe.setEndTime(DateUtils.parseDate(\"2099-12-31 23:59:59\", \"yyyy-MM-dd HH:mm:ss\"));\n } catch (ParseException e) {\n subscribe.setBeginTime(DateUtils.addYears(new Date(), 50));\n }\n if (Constants.VIID_SERVER.SUBSCRIBE_DETAIL.RAW.equals(subscribeDetail)) {\n subscribe.setReceiveAddr(String.format(\"ws://%s:%s/VIID/Subscribe/WebSocket\", server.getHost(), server.getPort()));\n } else {\n subscribe.setReceiveAddr(server.httpUrlBuilder() + \"/VIID/SubscribeNotifications\");\n }\n subscribe.setReportInterval(3);\n subscribe.setReason(\"测试\" + title);\n subscribe.setOperateType(0);\n subscribe.setSubscribeStatus(0);\n //0=卡口,1=设备,4=视图库\n subscribe.setResourceClass(0);\n subscribe.setResultImageDeclare(\"-1\");\n subscribe.setResultFeatureDeclare(1);\n return subscribe;\n }\n\n public static SubscribeObject castSubscribe(VIIDPublish entity) {\n if (Objects.nonNull(entity)) {\n SubscribeObject subscribe = new SubscribeObject();\n BeanUtils.copyProperties(entity, subscribe);\n return subscribe;\n }\n return null;\n }\n\n public static VIIDSubscribe castSubscribe(SubscribeObject subscribe) {\n VIIDSubscribe entity = new VIIDSubscribe();\n BeanUtils.copyProperties(subscribe, entity);\n return entity;\n }\n\n public static VIIDPublish castPublish(SubscribeObject subscribe) {\n VIIDPublish entity = new VIIDPublish();\n BeanUtils.copyProperties(subscribe, entity);\n return entity;\n }\n\n public static APEDevice castApeDevice(APEObject src) {\n APEDevice entity = new APEDevice();\n entity.setApeId(src.getApeID());\n entity.setName(src.getName());\n entity.setModel(src.getModel());\n entity.setIpAddr(src.getIPAddr());\n entity.setPort(src.getPort());\n entity.setLongitude(src.getLongitude());\n entity.setLatitude(src.getLatitude());\n entity.setPlaceCode(src.getPlaceCode());\n entity.setIsOnline(src.getIsOnline());\n entity.setUserId(src.getUserId());\n entity.setPassword(src.getPassword());\n entity.setFunctionType(src.getFunctionType());\n return entity;\n }\n\n public static SubscribeObject castPublish(VIIDPublish publish) {\n SubscribeObject subscribe = new SubscribeObject();\n BeanUtils.copyProperties(publish, subscribe);\n return subscribe;\n }\n\n public static TollgateDevice castTollgateDevice(TollgateObject src) {\n TollgateDevice device = new TollgateDevice();\n device.setTollgateID(src.getTollgateID());\n device.setLaneNum(src.getLaneNum());\n device.setLatitude(src.getLatitude());\n device.setLongitude(src.getLongitude());\n device.setName(src.getName());\n device.setOrgCode(src.getOrgCode());\n device.setPlaceCode(src.getPlaceCode());\n device.setStatus(src.getStatus());\n device.setTollgateCat(src.getTollgateCat());\n device.setTollgateUsage(src.getTollgateUsage());\n return device;\n }\n\n private static String randomSubscriberId(String organization) {\n if (StringUtils.length(organization) < 6)\n organization = \"431000\";\n String prefix = organization.substring(0, 6);\n String suffix = \"000000\";\n String op = \"03\";\n String timestamp = DateFormatUtils.format(new Date(), \"yyyyMMddHHmm\");\n String random = RandomStringUtils.randomNumeric(7);\n // 6+6+2+12+7\n return prefix + suffix + op + timestamp + random;\n }\n\n}" } ]
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cz.viid.fe.domain.VIIDSubscribeRequest; import com.cz.viid.framework.config.Constants; import com.cz.viid.framework.config.RedisConfig; import com.cz.viid.framework.domain.dto.ResponseStatusObject; import com.cz.viid.framework.domain.dto.SubscribeObject; import com.cz.viid.framework.domain.entity.VIIDServer; import com.cz.viid.framework.domain.entity.VIIDSubscribe; import com.cz.viid.framework.domain.vo.SubscribesRequest; import com.cz.viid.framework.domain.vo.VIIDSubscribesResponse; import com.cz.viid.framework.mapper.VIIDSubscribeMapper; import com.cz.viid.framework.service.VIIDServerService; import com.cz.viid.framework.service.VIIDSubscribeService; import com.cz.viid.rpc.VIIDServerClient; import com.cz.viid.utils.StructCodec; import org.apache.commons.lang3.StringUtils; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Objects;
6,545
package com.cz.viid.framework.service.impl; @Service public class VIIDSubscribeServiceImpl extends ServiceImpl<VIIDSubscribeMapper, VIIDSubscribe> implements VIIDSubscribeService { @Resource VIIDServerService viidServerService; @Resource VIIDServerClient viidServerClient; @Cacheable(cacheNames = RedisConfig.CACHE_15MIN, key = "'SubscribeEntityService::getCacheById::' + #subscribeId", unless = "#result == null") @Override public VIIDSubscribe getCacheById(String subscribeId) { return getById(subscribeId); } @Override public VIIDSubscribesResponse subscribes(VIIDSubscribeRequest request) { VIIDServer setting = viidServerService.getCurrentServer(); VIIDServer domain = viidServerService.getById(request.getServerId()); String resourceUri = assembleResourceUri(request); SubscribeObject subscribe = StructCodec.inputSubscribeBuilder(resourceUri, request.getTitle(), request.getSubscribeDetail(), domain); subscribe.setResourceClass(request.getResourceClass()); //发送订阅请求 URI uri = URI.create(domain.httpUrlBuilder()); VIIDSubscribesResponse response = viidServerClient.addSubscribes(uri, SubscribesRequest.create(subscribe), setting.getServerId()); VIIDSubscribe entity = StructCodec.castSubscribe(subscribe); entity.setSubscribeDetail(request.getSubscribeDetail()); entity.setServerId(request.getServerId()); this.save(entity); return VIIDSubscribesResponse.create(response.getResponseStatusListObject().getResponseStatusObject()); } @Override public VIIDSubscribesResponse unSubscribes(VIIDSubscribeRequest request) { VIIDServer setting = viidServerService.getCurrentServer(); VIIDSubscribe subscribe = this.getById(request.getSubscribeId()); if (Objects.isNull(subscribe)) return VIIDSubscribesResponse.create(
package com.cz.viid.framework.service.impl; @Service public class VIIDSubscribeServiceImpl extends ServiceImpl<VIIDSubscribeMapper, VIIDSubscribe> implements VIIDSubscribeService { @Resource VIIDServerService viidServerService; @Resource VIIDServerClient viidServerClient; @Cacheable(cacheNames = RedisConfig.CACHE_15MIN, key = "'SubscribeEntityService::getCacheById::' + #subscribeId", unless = "#result == null") @Override public VIIDSubscribe getCacheById(String subscribeId) { return getById(subscribeId); } @Override public VIIDSubscribesResponse subscribes(VIIDSubscribeRequest request) { VIIDServer setting = viidServerService.getCurrentServer(); VIIDServer domain = viidServerService.getById(request.getServerId()); String resourceUri = assembleResourceUri(request); SubscribeObject subscribe = StructCodec.inputSubscribeBuilder(resourceUri, request.getTitle(), request.getSubscribeDetail(), domain); subscribe.setResourceClass(request.getResourceClass()); //发送订阅请求 URI uri = URI.create(domain.httpUrlBuilder()); VIIDSubscribesResponse response = viidServerClient.addSubscribes(uri, SubscribesRequest.create(subscribe), setting.getServerId()); VIIDSubscribe entity = StructCodec.castSubscribe(subscribe); entity.setSubscribeDetail(request.getSubscribeDetail()); entity.setServerId(request.getServerId()); this.save(entity); return VIIDSubscribesResponse.create(response.getResponseStatusListObject().getResponseStatusObject()); } @Override public VIIDSubscribesResponse unSubscribes(VIIDSubscribeRequest request) { VIIDServer setting = viidServerService.getCurrentServer(); VIIDSubscribe subscribe = this.getById(request.getSubscribeId()); if (Objects.isNull(subscribe)) return VIIDSubscribesResponse.create(
Collections.singletonList(new ResponseStatusObject("", "500", "订阅不存在"))
2
2023-10-23 11:25:43+00:00
8k
eclipse-egit/egit
org.eclipse.egit.gitflow.test/src/org/eclipse/egit/gitflow/op/FeatureFinishOperationTest.java
[ { "identifier": "BranchOperation", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/op/BranchOperation.java", "snippet": "public class BranchOperation implements IEGitOperation {\n\n\tprivate final String target;\n\n\tprivate Repository[] repositories;\n\n\tprivate @NonNull Map<Repository, CheckoutResult> results = new HashMap<>();\n\n\tprivate boolean delete;\n\n\t/**\n\t * Construct a {@link BranchOperation} object for a {@link Ref}.\n\t *\n\t * @param repository\n\t * @param target\n\t * a {@link Ref} name or {@link RevCommit} id\n\t */\n\tpublic BranchOperation(Repository repository, String target) {\n\t\tthis(repository, target, true);\n\t}\n\n\t/**\n\t * Construct a {@link BranchOperation} object for a {@link Ref}.\n\t *\n\t * @param repository\n\t * @param target\n\t * a {@link Ref} name or {@link RevCommit} id\n\t * @param delete\n\t * true to delete missing projects on new branch, false to close\n\t * them\n\t */\n\tpublic BranchOperation(Repository repository, String target, boolean delete) {\n\t\tthis(new Repository[] { repository }, target, delete);\n\t}\n\n\t/**\n\t *\n\t * @param repositories\n\t * @param target\n\t * @param delete\n\t */\n\tpublic BranchOperation(Repository[] repositories, String target,\n\t\t\tboolean delete) {\n\t\tthis.repositories = repositories;\n\t\tthis.target = target;\n\t\tthis.delete = delete;\n\t}\n\n\t@Override\n\tpublic void execute(IProgressMonitor m) throws CoreException {\n\t\tIWorkspaceRunnable action = new IWorkspaceRunnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run(IProgressMonitor pm) throws CoreException {\n\t\t\t\ttry {\n\t\t\t\t\tpm.setTaskName(MessageFormat.format(\n\t\t\t\t\t\t\tCoreText.BranchOperation_performingBranch, target));\n\t\t\t\t\tint numberOfRepositories = repositories.length;\n\t\t\t\t\tSubMonitor progress = SubMonitor.convert(pm,\n\t\t\t\t\t\t\tnumberOfRepositories * 2);\n\t\t\t\t\tfor (Repository repository : repositories) {\n\t\t\t\t\t\tCheckoutResult result;\n\t\t\t\t\t\tif (pm.isCanceled()) {\n\t\t\t\t\t\t\t// don't break from the loop, the result map must be\n\t\t\t\t\t\t\t// filled\n\t\t\t\t\t\t\tresult = CheckoutResult.NOT_TRIED_RESULT;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresult = checkoutRepository(repository,\n\t\t\t\t\t\t\t\t\tprogress.newChild(1),\n\t\t\t\t\t\t\t\t\tnumberOfRepositories > 1);\n\t\t\t\t\t\t\tif (result.getStatus() == Status.NONDELETED) {\n\t\t\t\t\t\t\t\tretryDelete(repository,\n\t\t\t\t\t\t\t\t\t\tresult.getUndeletedList());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults.put(repository, result);\n\t\t\t\t\t}\n\t\t\t\t\trefreshAffectedProjects(\n\t\t\t\t\t\t\tprogress.newChild(numberOfRepositories));\n\t\t\t\t} finally {\n\t\t\t\t\tpm.done();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpublic CheckoutResult checkoutRepository(Repository repo,\n\t\t\t\t\tIProgressMonitor monitor, boolean logErrors)\n\t\t\t\t\tthrows CoreException {\n\t\t\t\tSubMonitor progress = SubMonitor.convert(monitor, 2);\n\t\t\t\tcloseProjectsMissingAfterCheckout(repo, progress.newChild(1));\n\t\t\t\ttry (Git git = new Git(repo)) {\n\t\t\t\t\tCheckoutCommand co = git.checkout().setProgressMonitor(\n\t\t\t\t\t\t\tnew EclipseGitProgressTransformer(\n\t\t\t\t\t\t\t\t\tprogress.newChild(1)));\n\t\t\t\t\tco.setName(target);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tco.call();\n\t\t\t\t\t} catch (CheckoutConflictException e) {\n\t\t\t\t\t\t// Covered by the status return below.\n\t\t\t\t\t} catch (JGitInternalException | GitAPIException e) {\n\t\t\t\t\t\tString msg = MessageFormat.format(\n\t\t\t\t\t\t\t\tCoreText.BranchOperation_checkoutError,\n\t\t\t\t\t\t\t\ttarget, repo.getDirectory());\n\t\t\t\t\t\tif (logErrors) {\n\t\t\t\t\t\t\tActivator.logError(msg, e);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow new CoreException(Activator.error(msg, e));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn co.getResult();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprivate void closeProjectsMissingAfterCheckout(Repository repo,\n\t\t\t\t\tIProgressMonitor monitor) throws CoreException {\n\t\t\t\tIProject[] missing = getMissingProjects(repo, target, monitor);\n\n\t\t\t\tif (missing.length > 0) {\n\t\t\t\t\tSubMonitor closeMonitor = SubMonitor.convert(monitor,\n\t\t\t\t\t\t\tmissing.length);\n\t\t\t\t\tcloseMonitor.setWorkRemaining(missing.length);\n\t\t\t\t\tfor (IProject project : missing) {\n\t\t\t\t\t\tif (closeMonitor.isCanceled()) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcloseMonitor.subTask(MessageFormat.format(\n\t\t\t\t\t\t\t\tCoreText.BranchOperation_closingMissingProject,\n\t\t\t\t\t\t\t\tproject.getName()));\n\t\t\t\t\t\tproject.close(closeMonitor.newChild(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprivate void refreshAffectedProjects(IProgressMonitor monitor)\n\t\t\t\t\tthrows CoreException {\n\t\t\t\tIProject[] refreshProjects = results.entrySet().stream()\n\t\t\t\t\t\t.map(this::getAffectedProjects)\n\t\t\t\t\t\t.flatMap(Stream::of).distinct()\n\t\t\t\t\t\t.toArray(IProject[]::new);\n\t\t\t\tProjectUtil.refreshValidProjects(refreshProjects, delete,\n\t\t\t\t\t\tmonitor);\n\t\t\t}\n\n\t\t\tprivate IProject[] getAffectedProjects(\n\t\t\t\t\tEntry<Repository, CheckoutResult> entry) {\n\t\t\t\tCheckoutResult result = entry.getValue();\n\n\t\t\t\tif (result.getStatus() != Status.OK\n\t\t\t\t\t\t&& result.getStatus() != Status.NONDELETED) {\n\t\t\t\t\t// the checkout did not succeed\n\t\t\t\t\treturn new IProject[0];\n\t\t\t\t}\n\n\t\t\t\tRepository repo = entry.getKey();\n\t\t\t\tList<String> pathsToHandle = new ArrayList<>();\n\t\t\t\tpathsToHandle.addAll(result.getModifiedList());\n\t\t\t\tpathsToHandle.addAll(result.getRemovedList());\n\t\t\t\tpathsToHandle.addAll(result.getConflictList());\n\t\t\t\tIProject[] refreshProjects = ProjectUtil\n\t\t\t\t\t\t.getProjectsContaining(repo, pathsToHandle);\n\t\t\t\treturn refreshProjects;\n\t\t\t}\n\t\t};\n\t\t// lock workspace to protect working tree changes\n\t\tResourcesPlugin.getWorkspace().run(action, getSchedulingRule(),\n\t\t\t\tIWorkspace.AVOID_UPDATE, m);\n\t}\n\n\t@Override\n\tpublic ISchedulingRule getSchedulingRule() {\n\t\treturn RuleUtil.getRuleForRepositories(Arrays.asList(repositories));\n\t}\n\n\t/**\n\t * @return the result of the operation\n\t */\n\t@NonNull\n\tpublic Map<Repository, CheckoutResult> getResults() {\n\t\treturn results;\n\t}\n\n\t/**\n\t * @param repo\n\t * @return return the result specific to a repository\n\t */\n\tpublic CheckoutResult getResult(Repository repo) {\n\t\tCheckoutResult result = results.get(repo);\n\t\tif (result == null) {\n\t\t\treturn CheckoutResult.NOT_TRIED_RESULT;\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid retryDelete(Repository repo, List<String> pathList) {\n\t\t// try to delete, but for a short time only\n\t\tlong startTime = System.currentTimeMillis();\n\t\tfor (String path : pathList) {\n\t\t\tif (System.currentTimeMillis() - startTime > 1000) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tFile fileToDelete = new File(repo.getWorkTree(), path);\n\t\t\tif (fileToDelete.exists()) {\n\t\t\t\ttry {\n\t\t\t\t\t// Only files should be passed here, thus\n\t\t\t\t\t// we ignore attempt to delete submodules when\n\t\t\t\t\t// we switch to a branch without a submodule\n\t\t\t\t\tif (!fileToDelete.isFile()) {\n\t\t\t\t\t\tFileUtils.delete(fileToDelete, FileUtils.RETRY);\n\t\t\t\t\t}\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// ignore here\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Compute the current projects that will be missing after the given branch\n\t * is checked out\n\t *\n\t * @param repository\n\t * @param branch\n\t * @param monitor\n\t * @return non-null but possibly empty array of missing projects\n\t * @throws CoreException\n\t */\n\tprivate IProject[] getMissingProjects(Repository repository,\n\t\t\tString branch, IProgressMonitor monitor) throws CoreException {\n\t\tIProject[] openProjects = ProjectUtil.getValidOpenProjects(repository);\n\t\tif (delete || openProjects.length == 0) {\n\t\t\treturn new IProject[0];\n\t\t}\n\t\tObjectId targetTreeId;\n\t\tObjectId currentTreeId;\n\t\ttry {\n\t\t\ttargetTreeId = repository.resolve(branch + \"^{tree}\"); //$NON-NLS-1$\n\t\t\tcurrentTreeId = repository.resolve(Constants.HEAD + \"^{tree}\"); //$NON-NLS-1$\n\t\t} catch (IOException e) {\n\t\t\treturn new IProject[0];\n\t\t}\n\t\tif (targetTreeId == null || currentTreeId == null) {\n\t\t\treturn new IProject[0];\n\t\t}\n\t\tMap<File, IProject> locations = new HashMap<>();\n\t\tfor (IProject project : openProjects) {\n\t\t\tif (monitor.isCanceled()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tIPath location = project.getLocation();\n\t\t\tif (location == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlocation = location\n\t\t\t\t\t.append(IProjectDescription.DESCRIPTION_FILE_NAME);\n\t\t\tlocations.put(location.toFile(), project);\n\t\t}\n\n\t\tList<IProject> toBeClosed = new ArrayList<>();\n\t\tFile root = repository.getWorkTree();\n\t\ttry (TreeWalk walk = new TreeWalk(repository)) {\n\t\t\twalk.addTree(targetTreeId);\n\t\t\twalk.addTree(currentTreeId);\n\t\t\twalk.addTree(new FileTreeIterator(repository));\n\t\t\twalk.setRecursive(true);\n\t\t\twalk.setFilter(AndTreeFilter.create(PathSuffixFilter\n\t\t\t\t\t.create(IProjectDescription.DESCRIPTION_FILE_NAME),\n\t\t\t\t\tTreeFilter.ANY_DIFF));\n\t\t\twhile (walk.next()) {\n\t\t\t\tif (monitor.isCanceled()) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tAbstractTreeIterator targetIter = walk.getTree(0,\n\t\t\t\t\t\tAbstractTreeIterator.class);\n\t\t\t\tif (targetIter != null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tAbstractTreeIterator currentIter = walk.getTree(1,\n\t\t\t\t\t\tAbstractTreeIterator.class);\n\t\t\t\tAbstractTreeIterator workingIter = walk.getTree(2,\n\t\t\t\t\t\tAbstractTreeIterator.class);\n\t\t\t\tif (currentIter == null || workingIter == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tIProject project = locations.get(new File(root, walk\n\t\t\t\t\t\t.getPathString()));\n\t\t\t\tif (project != null) {\n\t\t\t\t\ttoBeClosed.add(project);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\treturn new IProject[0];\n\t\t}\n\t\treturn toBeClosed.toArray(new IProject[0]);\n\t}\n}" }, { "identifier": "GitFlowRepository", "path": "org.eclipse.egit.gitflow/src/org/eclipse/egit/gitflow/GitFlowRepository.java", "snippet": "public class GitFlowRepository {\n\n\tprivate Repository repository;\n\n\t/**\n\t * @param repository\n\t */\n\tpublic GitFlowRepository(@NonNull Repository repository) {\n\t\tthis.repository = repository;\n\t}\n\n\t/**\n\t * @return Whether or not this repository has branches.\n\t */\n\tpublic boolean hasBranches() {\n\t\tList<Ref> branches;\n\t\ttry {\n\t\t\tbranches = Git.wrap(repository).branchList().call();\n\t\t\treturn !branches.isEmpty();\n\t\t} catch (GitAPIException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * @param branch\n\t * @return Whether or not branch exists in this repository.\n\t * @throws GitAPIException\n\t */\n\tpublic boolean hasBranch(String branch) throws GitAPIException {\n\t\tString fullBranchName = R_HEADS + branch;\n\t\tList<Ref> branchList = Git.wrap(repository).branchList().call();\n\t\tfor (Ref ref : branchList) {\n\t\t\tif (fullBranchName.equals(ref.getTarget().getName())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * @param branchName\n\t * @return Ref for branchName.\n\t * @throws IOException\n\t */\n\tpublic Ref findBranch(String branchName) throws IOException {\n\t\treturn repository.exactRef(R_HEADS + branchName);\n\t}\n\n\t/**\n\t * @return current branch has feature-prefix?\n\t * @throws IOException\n\t */\n\tpublic boolean isFeature() throws IOException {\n\t\tString branch = repository.getBranch();\n\t\treturn branch != null\n\t\t\t\t&& branch.startsWith(getConfig().getFeaturePrefix());\n\t}\n\n\t/**\n\t * @return branch name has name \"develop\"?\n\t * @throws IOException\n\t */\n\tpublic boolean isDevelop() throws IOException {\n\t\tString branch = repository.getBranch();\n\t\treturn branch != null && branch.equals(getConfig().getDevelop());\n\t}\n\n\t/**\n\t * @return branch name has name \"master\"?\n\t * @throws IOException\n\t */\n\tpublic boolean isMaster() throws IOException {\n\t\tString branch = repository.getBranch();\n\t\treturn branch != null && branch.equals(getConfig().getMaster());\n\t}\n\n\t/**\n\t * @return current branch has release prefix?\n\t * @throws IOException\n\t */\n\tpublic boolean isRelease() throws IOException {\n\t\tString branch = repository.getBranch();\n\t\treturn branch != null\n\t\t\t\t&& branch.startsWith(getConfig().getReleasePrefix());\n\t}\n\n\t/**\n\t * @return current branch has hotfix prefix?\n\t * @throws IOException\n\t */\n\tpublic boolean isHotfix() throws IOException {\n\t\tString branch = repository.getBranch();\n\t\treturn branch != null\n\t\t\t\t&& branch.startsWith(getConfig().getHotfixPrefix());\n\t}\n\n\t/**\n\t * @return HEAD commit\n\t * @throws WrongGitFlowStateException\n\t */\n\tpublic RevCommit findHead() throws WrongGitFlowStateException {\n\t\ttry (RevWalk walk = new RevWalk(repository)) {\n\t\t\ttry {\n\t\t\t\tObjectId head = repository.resolve(HEAD);\n\t\t\t\tif (head == null) {\n\t\t\t\t\tthrow new WrongGitFlowStateException(\n\t\t\t\t\t\t\tCoreText.GitFlowRepository_gitFlowRepositoryMayNotBeEmpty);\n\t\t\t\t}\n\t\t\t\treturn walk.parseCommit(head);\n\t\t\t} catch (MissingObjectException e) {\n\t\t\t\tthrow new WrongGitFlowStateException(CoreText.GitFlowRepository_gitFlowRepositoryMayNotBeEmpty);\n\t\t\t} catch (RevisionSyntaxException | IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param branchName\n\t * @return HEAD commit on branch branchName or {@literal null} if\n\t * {@code branchName} could not be resolved.\n\t */\n\tpublic @Nullable RevCommit findHead(String branchName) {\n\t\ttry (RevWalk walk = new RevWalk(repository)) {\n\t\t\ttry {\n\t\t\t\tString revstr = R_HEADS + branchName;\n\t\t\t\tObjectId head = repository.resolve(revstr);\n\t\t\t\tif (head == null) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\treturn walk.parseCommit(head);\n\t\t\t} catch (RevisionSyntaxException | IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param sha1\n\t * @return Commit for SHA1\n\t */\n\tpublic RevCommit findCommit(String sha1) {\n\t\ttry (RevWalk walk = new RevWalk(repository)) {\n\t\t\ttry {\n\t\t\t\tObjectId head = repository.resolve(sha1);\n\t\t\t\treturn walk.parseCommit(head);\n\t\t\t} catch (RevisionSyntaxException | IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * @return JGit repository\n\t */\n\tpublic Repository getRepository() {\n\t\treturn repository;\n\t}\n\n\t/**\n\t * @return git flow feature branches\n\t */\n\tpublic List<Ref> getFeatureBranches() {\n\t\treturn getPrefixBranches(R_HEADS + getConfig().getFeaturePrefix());\n\t}\n\n\t/**\n\t * @return git flow release branches\n\t */\n\tpublic List<Ref> getReleaseBranches() {\n\t\treturn getPrefixBranches(R_HEADS + getConfig().getReleasePrefix());\n\t}\n\n\t/**\n\t * @return git flow hotfix branches\n\t */\n\tpublic List<Ref> getHotfixBranches() {\n\t\treturn getPrefixBranches(R_HEADS + getConfig().getHotfixPrefix());\n\t}\n\n\tprivate List<Ref> getPrefixBranches(String prefix) {\n\t\ttry {\n\t\t\tList<Ref> branches = Git.wrap(repository).branchList().call();\n\t\t\tList<Ref> prefixBranches = new ArrayList<>();\n\t\t\tfor (Ref ref : branches) {\n\t\t\t\tif (ref.getName().startsWith(prefix)) {\n\t\t\t\t\tprefixBranches.add(ref);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn prefixBranches;\n\t\t} catch (GitAPIException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * @param ref\n\t * @return branch name for ref\n\t */\n\tpublic String getFeatureBranchName(Ref ref) {\n\t\treturn ref.getName().substring(\n\t\t\t\t(R_HEADS + getConfig().getFeaturePrefix()).length());\n\t}\n\n\t/**\n\t * @param tagName\n\t * @return commit tag tagName points to\n\t * @throws MissingObjectException\n\t * @throws IncorrectObjectTypeException\n\t * @throws IOException\n\t */\n\tpublic RevCommit findCommitForTag(String tagName)\n\t\t\tthrows MissingObjectException, IncorrectObjectTypeException,\n\t\t\tIOException {\n\t\ttry (RevWalk revWalk = new RevWalk(repository)) {\n\t\t\tRef tagRef = repository.exactRef(R_TAGS + tagName);\n\t\t\tif (tagRef == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn revWalk.parseCommit(tagRef.getObjectId());\n\t\t}\n\t}\n\n\t/**\n\t * @param featureName\n\t * @param value\n\t * @throws IOException\n\t */\n\tpublic void setRemote(String featureName, String value) throws IOException {\n\t\tgetConfig().setRemote(featureName, value);\n\t}\n\n\t/**\n\t * @param featureName\n\t * @param value\n\t * @throws IOException\n\t */\n\tpublic void setUpstreamBranchName(String featureName, String value) throws IOException {\n\t\tgetConfig().setUpstreamBranchName(featureName, value);\n\t}\n\n\t/**\n\t * @param featureName\n\t * @return Upstream branch name\n\t */\n\tpublic String getUpstreamBranchName(String featureName) {\n\t\treturn getConfig().getUpstreamBranchName(featureName);\n\t}\n\n\t/**\n\t * @return the configuration of this repository\n\t */\n\tpublic GitFlowConfig getConfig() {\n\t\treturn new GitFlowConfig(repository.getConfig());\n\t}\n\n\t/**\n\t * Check if the given commit is an ancestor of the current HEAD on the\n\t * develop branch.\n\t *\n\t * @param selectedCommit\n\t * @return Whether or not the selected commit is on the develop branch.\n\t * @throws IOException\n\t * @since 4.3\n\t */\n\tpublic boolean isOnDevelop(@NonNull RevCommit selectedCommit) throws IOException {\n\t\tString develop = getConfig().getDevelopFull();\n\t\treturn isOnBranch(selectedCommit, develop);\n\t}\n\n\tprivate boolean isOnBranch(RevCommit commit, String fullBranch)\n\t\t\tthrows IOException {\n\t\tRef branchRef = repository.exactRef(fullBranch);\n\t\tif (branchRef == null) {\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tList<Ref> list = Git.wrap(repository).branchList().setContains(commit.name()).call();\n\n\t\t\treturn list.contains(branchRef);\n\t\t} catch (GitAPIException e) {\n\t\t\t// ListBranchCommand can only throw a wrapped IOException\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n}" }, { "identifier": "WrongGitFlowStateException", "path": "org.eclipse.egit.gitflow/src/org/eclipse/egit/gitflow/WrongGitFlowStateException.java", "snippet": "public class WrongGitFlowStateException extends Exception {\n\n\t/**\n\t * @generated\n\t */\n\tprivate static final long serialVersionUID = 3091117695421525438L;\n\n\t/**\n\t * @param e\n\t */\n\tpublic WrongGitFlowStateException(Exception e) {\n\t\tsuper(e);\n\t}\n\n\t/**\n\t * @param string\n\t */\n\tpublic WrongGitFlowStateException(String string) {\n\t\tsuper(string);\n\t}\n}" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import org.eclipse.egit.core.op.BranchOperation; import org.eclipse.egit.gitflow.GitFlowRepository; import org.eclipse.egit.gitflow.WrongGitFlowStateException; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Status; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Test;
5,095
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.gitflow.op; public class FeatureFinishOperationTest extends AbstractFeatureOperationTest { @Test public void testFeatureFinishFastForward() throws Exception { String fileName = "theFirstFile.txt"; Repository repository = testRepository.getRepository();
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.gitflow.op; public class FeatureFinishOperationTest extends AbstractFeatureOperationTest { @Test public void testFeatureFinishFastForward() throws Exception { String fileName = "theFirstFile.txt"; Repository repository = testRepository.getRepository();
GitFlowRepository gfRepo = init("testFeatureFinish\n\nfirst commit\n");
1
2023-10-20 15:17:51+00:00
8k
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java
src/main/application/driver/adapter/usecase/Game.java
[ { "identifier": "BigBoard", "path": "src/main/application/driver/adapter/usecase/board/BigBoard.java", "snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\n private static final int COLUMNS = 8;\n\n public BigBoard(final List<Enemy> enemies) {\n squares = new Enemy[ROWS][COLUMNS];\n int indexEnemy = 0;\n SQUARE_LOOP: for (int row = 0; row < ROWS; row++) {\n for (int column = 0; column < COLUMNS; column++) {\n if (indexEnemy < enemies.size()) {\n \tsquares[row][column] = enemies.get(indexEnemy);\n indexEnemy++;\n } else {\n break SQUARE_LOOP;\n }\n }\n }\n this.iterator = new BoardIterator(this);\n }\n\n\t@Override\n public int getRows() {\n return ROWS;\n }\n\n\t@Override\n public int getColumns() {\n return COLUMNS;\n }\n\n\t@Override\n public Enemy getEnemy(final int row, final int column) {\n return squares[row][column];\n }\n\n\t@Override\n\tpublic void deleteEnemy(final int row, final int column) {\n SQUARE_LOOP: for (int rowCurrent = row; rowCurrent < ROWS; rowCurrent++) {\n for (int columnCurrent = column; columnCurrent < COLUMNS; columnCurrent++) {\n \tif ((rowCurrent != ROWS - 1) || (columnCurrent != COLUMNS - 1)) {\n \t\tfinal int rowNext;\n \t\tfinal int columnNext = columnCurrent < COLUMNS - 1 ? columnCurrent + 1 : 0;\n \t\tif (columnCurrent == COLUMNS - 1) {\n \t\trowNext = rowCurrent < ROWS - 1 ? rowCurrent + 1 : 0;\n \t\t} else {\n \t\t\trowNext = rowCurrent;\n \t\t}\n \tfinal Enemy enemyNext = squares[rowNext][columnNext];\n \tif (enemyNext == null) {\n \tsquares[rowCurrent][columnCurrent] = null;\n \t\tbreak SQUARE_LOOP;\n \t}\n \tsquares[rowCurrent][columnCurrent] = enemyNext;\n \t} else {\n \tsquares[rowCurrent][columnCurrent] = null;\n break SQUARE_LOOP;\n \t}\n }\n }\n }\n\n\t@Override\n\tpublic String getAvatarSquare(final int row, final int column) {\n\t\tfinal Enemy enemy = squares[row][column];\n\t\tfinal StringBuilder avatarSquare = new StringBuilder();\n\t\tif (enemy != null) {\n\t\t\tavatarSquare.append(\"{\");\n\t\t\tavatarSquare.append(row);\n\t\t\tavatarSquare.append(\"-\");\n\t\t\tavatarSquare.append(column);\n\t\t\tavatarSquare.append(\":\");\n\t\t\tfinal String avatar = enemy.getAvatar(\"\");\n\t\t\tavatarSquare.append(!avatar.isEmpty() ? avatar.substring(0, avatar.length() - 1) : \"\");\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getLife());\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getAttackLevel(false));\n\t\t\tavatarSquare.append(\"}\");\n\t\t\tif (column == COLUMNS - 1) {\n\t\t\t\tavatarSquare.append(\"\\n\");\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn avatarSquare.toString();\n\t}\n\n\t@Override\n\tpublic PatternsIterator<Enemy> getIterator() {\n\t\treturn this.iterator;\n\t}\n\n}" }, { "identifier": "ConjunctionExpression", "path": "src/main/application/driver/adapter/usecase/expression/ConjunctionExpression.java", "snippet": "public class ConjunctionExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic ConjunctionExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tList<String> avatarSquares = new ArrayList<>(leftAvatarSquares);\n\t\tavatarSquares.retainAll(rightAvatarSquares);\n return avatarSquares;\n\t}\n\n}" }, { "identifier": "Context", "path": "src/main/application/driver/adapter/usecase/expression/Context.java", "snippet": "public class Context {\n\tprivate final List<String> avatarSquares;\n\t\n\tpublic Context(final List<String> avatarSquares) {\n\t\tthis.avatarSquares = avatarSquares;\n\t}\n\t\n\tpublic List<String> getAvatarSquares() {\n\t\treturn this.avatarSquares;\n\t}\n}" }, { "identifier": "AlternativeExpression", "path": "src/main/application/driver/adapter/usecase/expression/AlternativeExpression.java", "snippet": "public class AlternativeExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic AlternativeExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tSet<String> avatarSquares = new LinkedHashSet<>(leftAvatarSquares);\n\t\tavatarSquares.addAll(rightAvatarSquares);\n return new ArrayList<>(avatarSquares);\n\t}\n\n}" }, { "identifier": "EnemyExpression", "path": "src/main/application/driver/adapter/usecase/expression/EnemyExpression.java", "snippet": "public class EnemyExpression implements Expression {\n\tprivate final String word;\n\n\tpublic EnemyExpression(String word) {\n\t\tthis.word = switch(word.toLowerCase()) {\n\t\tcase \"soldado\" -> \"S\";\n\t\tcase \"aire\" -> \"A\";\n\t\tcase \"naval\" -> \"N\";\n\t\tcase \"fortaleza\" -> \"F\";\n\t\tcase \"escuadron\", \"escuadrón\" -> \"E\";\n\t\tcase \"supremo\", \"maestro\", \"jefe\" -> \"J\";\n\t\tdefault -> word.toUpperCase();\n\t\t};\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n return context.getAvatarSquares().stream()\n .filter(avatarSquare -> avatarSquare.contains(this.word))\n .toList();\n\t}\n\n}" }, { "identifier": "EnemyBasicMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyBasicMethod.java", "snippet": "public class EnemyBasicMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyBasicMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<Enemy>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Poison());\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 8;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 3)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Heat();\n\t\t\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyHighMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyHighMethod.java", "snippet": "public class EnemyHighMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyHighMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 5;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t}\n\n\t\t// soldiers with fort\n final int quantitySoldiersWithFork = 2;\n\t\tfor (int created = 1; created <= quantitySoldiersWithFork; created++) {\n\t\t\tenemies.add(new Fort(soldierEnemyBase.clone()));\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tEnemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));\n\t\t\tif (createdSquadron == 1) {\n\t\t\t\tsquadron = new Fort(squadron);\n\t\t\t}\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 4;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Heat();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new Rainy();\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentFifth = new City(83);\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\tfavorableEnvironmentFourth.setNextFavorableEnvironment(favorableEnvironmentFifth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyMiddleMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyMiddleMethod.java", "snippet": "public class EnemyMiddleMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyMiddleMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(2));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 6;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 2)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tfinal Enemy squadron = armyFactory.createSquadron(soldiers, new Poison());\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 3;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new MultipleShots(2));\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new City(83);\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Heat();\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "BasicMission", "path": "src/main/application/driver/adapter/usecase/mission/BasicMission.java", "snippet": "public class BasicMission extends Mission {\n\n\tpublic BasicMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 150;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n}" }, { "identifier": "HighMission", "path": "src/main/application/driver/adapter/usecase/mission/HighMission.java", "snippet": "public class HighMission extends Mission {\n\n\tpublic HighMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isSupremeDead = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisSupremeDead = enemy.getLife() <= 0;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSupremeDead;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tboolean isFortAlive = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tif(this.enemyIterator.getNext() instanceof Fort) {\n\t\t\t\tisFortAlive = false;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isFortAlive;\n\t}\n\n}" }, { "identifier": "MiddleMission", "path": "src/main/application/driver/adapter/usecase/mission/MiddleMission.java", "snippet": "public class MiddleMission extends Mission {\n\n\tpublic MiddleMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 80;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tint squadronsAlive = 0;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SquadronAir || enemy instanceof SquadronNaval) {\n\t\t\t\t++squadronsAlive;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn squadronsAlive <= 1;\n\t}\n\n}" }, { "identifier": "EnemyMethod", "path": "src/main/application/driver/port/usecase/EnemyMethod.java", "snippet": "public interface EnemyMethod {\n\tList<Enemy> createEnemies();\n\tFavorableEnvironment createFavorableEnvironments();\n}" }, { "identifier": "Expression", "path": "src/main/application/driver/port/usecase/Expression.java", "snippet": "public interface Expression {\n\tList<String> interpret(Context context);\n}" }, { "identifier": "GameableUseCase", "path": "src/main/application/driver/port/usecase/GameableUseCase.java", "snippet": "public interface GameableUseCase {\n\tvoid startGame();\n\tBoolean[] attackAndCounterAttack(int row, int column);\n\tBoolean[] attackWithComboAndCounterAttack(int row, int column);\n\tvoid calculateFreezing();\n\tboolean isFrozen();\n\tint getTurnsForDefrost();\n\tvoid plusTurnFrozen();\n\tString getStringAvatarSquares();\n\tString getStringAvatarPlayer();\n\tvoid removeDeadEnemies();\n\tString getEnemies(String stringExpression);\n\tvoid healing();\n\tboolean doOrRestoreBackup(String inputString);\n\tboolean isGameCompleted();\n\tboolean verifyAnUpLevel();\n}" }, { "identifier": "BoardCollection", "path": "src/main/application/driver/port/usecase/iterator/BoardCollection.java", "snippet": "public interface BoardCollection<T> {\n int getRows();\n int getColumns();\n Enemy getEnemy(int row, int column);\n\tvoid deleteEnemy(int row, int column);\n\tString getAvatarSquare(int row, int column);\n\tPatternsIterator<T> getIterator();\n}" }, { "identifier": "PatternsIterator", "path": "src/main/application/driver/port/usecase/iterator/PatternsIterator.java", "snippet": "public interface PatternsIterator<T> {\n\tboolean hasNext();\n T getNext();\n\tvoid remove();\n String getAvatarSquareNext();\n void reset();\n}" }, { "identifier": "ArmyFactory", "path": "src/main/domain/model/ArmyFactory.java", "snippet": "public interface ArmyFactory {\n\tPlayer createPlayer(PlayerBuilder playerBuilder);\n\tSoldier createSoldier(int life, int attackLevel, Skillfull skill);\n\tEnemy createSquadron(List<Enemy> squadron, Skillfull skill);\n\tSupreme getSupreme();\n}" }, { "identifier": "CaretakerPlayer", "path": "src/main/domain/model/CaretakerPlayer.java", "snippet": "public class CaretakerPlayer {\n private final Map<String, MementoPlayer> mementosPlayerByKey;\n \n public CaretakerPlayer() {\n \tthis.mementosPlayerByKey = new HashMap<>();\n }\n\n public void addMementoPlayerByKey(final String key, final MementoPlayer mementoPlayer) {\n \tthis.mementosPlayerByKey.put(key, mementoPlayer);\n }\n\n public MementoPlayer getMementoPlayerByKey(final String key) {\n return this.mementosPlayerByKey.get(key);\n }\n}" }, { "identifier": "Command", "path": "src/main/domain/model/Command.java", "snippet": "public interface Command {\n\tvoid execute();\n}" }, { "identifier": "Enemy", "path": "src/main/domain/model/Enemy.java", "snippet": "public abstract class Enemy implements Protective {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final Skillfull skill;\n\tprotected Status status;\n\t\n\tpublic Enemy(int life, int attackLevel, Skillfull skill) {\n\t\tthis.life = life;\n\t\tthis.attackLevel = attackLevel;\n\t\tthis.skill = skill;\n\t\tthis.status = new Asleep();\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel(boolean isAttacking) {\n\t\treturn this.skill.getEnhancedAttackLevel(this.attackLevel, isAttacking);\n\t}\n\t\n\tpublic int getCounterAttackLevel(final int attackLevelReceived) {\n\t\treturn this.status.getAttackLevel(attackLevelReceived, this);\n\t}\n\t\n\tpublic void setStatus(final Status status) {\n\t\tthis.status = status;\n\t}\n\t\n\t@Override\n\tpublic void protect(final Supreme theProtected) {\n\t\tthis.receiveAttack(1);\n\t\tif (this.getLife() <= 0) {\n\t\t\ttheProtected.removeProtector(this);\n\t\t}\n\t}\n\n\tpublic abstract void receiveAttack(final int attack);\n\t\n\tpublic abstract String getAvatar(final String prefix);\n\t\n\tpublic abstract void acceptVisit(Visitor visitor);\n}" }, { "identifier": "FavorableEnvironment", "path": "src/main/domain/model/FavorableEnvironment.java", "snippet": "public interface FavorableEnvironment {\n\tvoid setNextFavorableEnvironment(FavorableEnvironment favorableEnvironment);\n\tboolean canAttack(Enemy enemy);\n\tboolean canHandleAttack(Enemy enemy);\n}" }, { "identifier": "Healable", "path": "src/main/domain/model/Healable.java", "snippet": "public class Healable implements Visitor {\n\n\t@Override\n\tpublic void visitSoldier(Soldier soldier) {\n\t\tif (soldier.getTypeHair().equalsIgnoreCase(\"corto\")) {\n\t\t\tsoldier.life += 1;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void visitSquadron(Squadron squadron) {\n\t\tfor (Enemy enemy : squadron.squadronList) {\n\t\t\tenemy.acceptVisit(this);\n\t\t}\n\t\tsquadron.calculateLife();\n\t}\n\n\t@Override\n\tpublic void visitSupreme(Supreme supreme) {\n\t\tsupreme.life += 1;\n\t}\n\n\t@Override\n\tpublic void visitPlayer(Player player) {\n\t\tplayer.life += 50;\n\t}\n\n}" }, { "identifier": "Mission", "path": "src/main/domain/model/Mission.java", "snippet": "public abstract class Mission {\n\tprotected final BoardCollection<Enemy> board;\n\tprotected final PatternsIterator<Enemy> enemyIterator;\n\t\n\tpublic Mission(BoardCollection<Enemy> board) {\n\t\tthis.board = board;\n\t\tthis.enemyIterator = this.board.getIterator();\n\t}\n\t\n\tpublic boolean isMissionComplete() {\n\t\treturn this.isMainObjectiveComplete()\n\t\t\t\t&& this.isSecondaryObjectiveComplete()\n\t\t\t\t&& this.isTertiaryObjectiveComplete();\n\t}\n\n\tprotected abstract boolean isMainObjectiveComplete();\n\tprotected abstract boolean isSecondaryObjectiveComplete();\n\t\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\tboolean isSoldierAlive = false;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SoldierAir || enemy instanceof SoldierNaval) {\n\t\t\t\tisSoldierAlive = true;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSoldierAlive;\n\t}\n\n}" }, { "identifier": "Player", "path": "src/main/domain/model/Player.java", "snippet": "public abstract class Player {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final String name;\n\tprotected final Type type;\n\tprotected final String typeEye;\n\tprotected final String typeHair;\n\tprotected final String typeShirt;\n\tprotected final String typePant;\n\tprotected final String typeShoes;\n\t\n\tpublic Player(final PlayerBuilder builder) {\n\t\tthis.life = 250;\n\t\tthis.attackLevel = 10;\n\t\tthis.name = builder.name() != null && builder.name() != \"\" ? builder.name() : \"NN\";\n\t\tthis.type = builder.type() != null ? builder.type() : new WarriorType();\n\t\tthis.typeEye = builder.typeEye() != null && builder.typeEye() != \"\" ? builder.typeEye() : \"lentes\";\n\t\tthis.typeHair = builder.typeHair() != null && builder.typeHair() != \"\" ? builder.typeHair() : \"corto\";\n\t\tthis.typeShirt = builder.typeShirt() != null && builder.typeShirt() != \"\" ? builder.typeShirt() : \"franela\";\n\t\tthis.typePant = builder.typePant() != null && builder.typePant() != \"\" ? builder.typePant() : \"largos\";\n\t\tthis.typeShoes = builder.typeShoes() != null && builder.typeShoes() != \"\" ? builder.typeShoes() : \"tennis\";\n\t}\n\t\n\tpublic abstract String getAvatar();\n\t\n\tpublic void acceptVisit(Visitor visitor) {\n\t\tvisitor.visitPlayer(this);\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel() {\n\t\treturn this.attackLevel;\n\t}\n\t\n\tpublic void receiveAttack(final int attack) {\n\t\tthis.life -= attack;\n\t}\n\t\n\tpublic MementoPlayer doBackup() {\n\t\treturn new MementoPlayer(this);\n\t}\n\t\n\tpublic void restoreMemento(final MementoPlayer memento) {\n\t\tthis.life = memento.life;\n\t\tthis.attackLevel = memento.attackLevel;\n\t}\n\t\n\tpublic class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\t\tprivate final int life;\n\t\tprivate final int attackLevel;\n\t\t\n\t\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\t\tpublic MementoPlayer(Player player) {\n\t\t\tthis.life = player.life;\n\t\t\tthis.attackLevel = player.attackLevel;\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "MementoPlayer", "path": "src/main/domain/model/Player.java", "snippet": "public class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\tprivate final int life;\n\tprivate final int attackLevel;\n\t\t\n\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\tpublic MementoPlayer(Player player) {\n\t\tthis.life = player.life;\n\t\tthis.attackLevel = player.attackLevel;\n\t}\n\t\t\n}" }, { "identifier": "Attack", "path": "src/main/domain/model/command/Attack.java", "snippet": "public class Attack implements Command {\n\tprivate final FavorableEnvironment favorableEnvironments;\n\tprivate final int playerAttackLevel;\n\tprivate final Enemy enemy;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic Attack(final FavorableEnvironment favorableEnvironments, final int playerAttackLevel, final Enemy enemy) {\n\t\tthis.favorableEnvironments = favorableEnvironments;\n\t\tthis.playerAttackLevel = playerAttackLevel;\n\t\tthis.enemy = enemy;\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tif (this.enemy.getLife() > 0) { //esta propiedad como excepción a la regla se permite ser mutable ya que cuando se ejecute el comando el enemigo ya podría estar muerto\n\t\t\tfinal boolean isSuccessfulAttack = this.favorableEnvironments.canAttack(this.enemy);\n\t\t\tif (isSuccessfulAttack) {\n\t\t\t\tthis.enemy.receiveAttack(this.playerAttackLevel);\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "HealingPlayer", "path": "src/main/domain/model/command/HealingPlayer.java", "snippet": "public class HealingPlayer implements Command {\n\tprivate final Player player;\n\tprivate final Visitor healable;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic HealingPlayer(Player player) {\n\t\tthis.player = player;\n\t\tthis.healable = new Healable();\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tthis.player.acceptVisit(this.healable);\n\t}\n\n}" }, { "identifier": "Visitor", "path": "src/main/domain/model/Visitor.java", "snippet": "public interface Visitor {\n\tvoid visitSoldier(Soldier soldier);\n\tvoid visitSquadron(Squadron squadron);\n\tvoid visitSupreme(Supreme supreme);\n\tvoid visitPlayer(Player player);\n}" } ]
import java.util.ArrayList; import java.util.List; import main.application.driver.adapter.usecase.board.BigBoard; import main.application.driver.adapter.usecase.expression.ConjunctionExpression; import main.application.driver.adapter.usecase.expression.Context; import main.application.driver.adapter.usecase.expression.AlternativeExpression; import main.application.driver.adapter.usecase.expression.EnemyExpression; import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod; import main.application.driver.adapter.usecase.mission.BasicMission; import main.application.driver.adapter.usecase.mission.HighMission; import main.application.driver.adapter.usecase.mission.MiddleMission; import main.application.driver.port.usecase.EnemyMethod; import main.application.driver.port.usecase.Expression; import main.application.driver.port.usecase.GameableUseCase; import main.application.driver.port.usecase.iterator.BoardCollection; import main.application.driver.port.usecase.iterator.PatternsIterator; import main.domain.model.ArmyFactory; import main.domain.model.CaretakerPlayer; import main.domain.model.Command; import main.domain.model.Enemy; import main.domain.model.FavorableEnvironment; import main.domain.model.Healable; import main.domain.model.Mission; import main.domain.model.Player; import main.domain.model.Player.MementoPlayer; import main.domain.model.command.Attack; import main.domain.model.command.HealingPlayer; import main.domain.model.Visitor;
7,160
package main.application.driver.adapter.usecase; public class Game implements GameableUseCase { private final ArmyFactory armyFactory; private EnemyMethod enemyMethod;
package main.application.driver.adapter.usecase; public class Game implements GameableUseCase { private final ArmyFactory armyFactory; private EnemyMethod enemyMethod;
private final Player player;
23
2023-10-20 18:36:47+00:00
8k
greatwqs/finance-manager
src/main/java/com/github/greatwqs/app/service/impl/UserServiceImpl.java
[ { "identifier": "AppException", "path": "src/main/java/com/github/greatwqs/app/common/exception/AppException.java", "snippet": "public class AppException extends RuntimeException {\n\n private ErrorCode errorCode;\n\n // rewrite default msg in i18n/message.properties\n private String errorMsg;\n\n private List<Object> errorMsgParams;\n\n /***\n * use default msg in i18n/message.properties\n * @param errorCode\n */\n public AppException(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n /***\n * use default msg with ${errorMsgParams} in i18n/message.properties\n * @param errorCode\n * @param errorMsgParams\n */\n public AppException(ErrorCode errorCode, List<Object> errorMsgParams) {\n this.errorCode = errorCode;\n this.errorMsgParams = errorMsgParams;\n }\n\n /***\n * rewrite default msg\n * @param errorCode\n * @param errorMsg\n */\n public AppException(ErrorCode errorCode, String errorMsg) {\n this.errorCode = errorCode;\n this.errorMsg = errorMsg;\n }\n\n public ErrorCode getErrorCode() {\n return errorCode;\n }\n\n public void setErrorCode(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n public String getErrorMsg() {\n return errorMsg;\n }\n\n public void setErrorMsg(String errorMsg) {\n this.errorMsg = errorMsg;\n }\n\n public List<Object> getErrorMsgParams() {\n return errorMsgParams;\n }\n\n public void setErrorMsgParams(List<Object> errorMsgParams) {\n this.errorMsgParams = errorMsgParams;\n }\n}" }, { "identifier": "ErrorCode", "path": "src/main/java/com/github/greatwqs/app/common/exception/ErrorCode.java", "snippet": "public enum ErrorCode {\n\n /**\n * HTTP STATUS CODE [0-1000)\n **/\n NORMAL_SUCCESS(200, HttpStatus.OK.value()),\n BAD_REQUEST(400, HttpStatus.BAD_REQUEST.value()),\n UNAUTHORIZED(401, HttpStatus.UNAUTHORIZED.value()),\n FORBIDDEN(403, HttpStatus.FORBIDDEN.value()),\n NOT_FOUND(404, HttpStatus.NOT_FOUND.value()),\n METHOD_NOT_ALLOWED(405, HttpStatus.METHOD_NOT_ALLOWED.value()),\n CONFLICT(409, HttpStatus.CONFLICT.value()),\n UNSUPPORTED_MEDIA_TYPE(415, HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()),\n INTERNAL_SERVER_ERROR(500, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n\n /**\n * Bisiness ERROR [1000-2000)\n **/\n BIZ_UNKNOWN_ERROR(1000, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n USER_LOGIN_ERROR(1001, HttpStatus.FOUND.value()),\n USER_LOGIN_TOKEN_ERROR(1002, HttpStatus.FOUND.value()),\n SUBJECT_NOT_FOUND(1003, HttpStatus.NOT_FOUND.value()),\n TICKET_TYPE_NOT_FOUND(1004, HttpStatus.NOT_FOUND.value()),\n ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE(1005, HttpStatus.BAD_REQUEST.value()),\n ORDER_NOT_FOUND(1006, HttpStatus.NOT_FOUND.value()),\n UPDATE_PASSWORD_CAN_NOT_EMPTY(1007, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_OLD_PASSWORD_NOT_MATCH(1008, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_CONFIRM_NOT_MATCH(1009, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_LENGTH_NOT_OK(1010, HttpStatus.BAD_REQUEST.value()),\n\n /**\n * Outer Call ERROR [2000+)\n **/\n OUT_UNKNOWN_ERROR(3000, HttpStatus.INTERNAL_SERVER_ERROR.value());\n\n\n private Integer errorCode;\n private Integer httpCode;\n private String errorMsgKey;\n\n ErrorCode(Integer errorCode, Integer httpCode) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n }\n\n ErrorCode(Integer errorCode, Integer httpCode, String errorMsgKey) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n this.errorMsgKey = errorMsgKey;\n }\n\n /***\n * get error message key.\n * @return example `error.code.2000`\n */\n public String getErrorMsgKey() {\n if (StringUtils.isNotEmpty(errorMsgKey)) {\n return errorMsgKey;\n }\n return AppConstants.ERROR_CODE_PREFIX_KEY + this.errorCode;\n }\n\n public Integer getErrorCode() {\n return errorCode;\n }\n\n public Integer getHttpCode() {\n return httpCode;\n }\n}" }, { "identifier": "UserLoginHistoryPo", "path": "src/main/java/com/github/greatwqs/app/domain/po/UserLoginHistoryPo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserLoginHistoryPo {\n private Long id;\n\n private Long userid;\n\n private String loginip;\n\n private String logintoken;\n\n private Date expiretime;\n\n private Boolean isvalid;\n\n private Date createtime;\n\n private Date updatetime;\n}" }, { "identifier": "UserVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/UserVo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserVo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\t@JsonIgnore\n\tprivate String password;\n\n\tprivate String address;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}" }, { "identifier": "UserManager", "path": "src/main/java/com/github/greatwqs/app/manager/UserManager.java", "snippet": "public interface UserManager {\n\n UserPo getPo(Long userId);\n\n UserPo getPoByName(String username);\n\n void insert(UserPo userPo);\n\n UserVo getVo(Long userId);\n\n void update(UserPo userPo);\n\n void delete(Long userId);\n}" }, { "identifier": "UserlistLoginHistoryMapper", "path": "src/main/java/com/github/greatwqs/app/mapper/UserlistLoginHistoryMapper.java", "snippet": "@Mapper\npublic interface UserlistLoginHistoryMapper {\n int deleteByPrimaryKey(Long id);\n\n int deleteByLoginToken(String loginToken);\n\n int insert(UserLoginHistoryPo record);\n\n int insertSelective(UserLoginHistoryPo record);\n\n UserLoginHistoryPo selectByPrimaryKey(Long id);\n\n UserLoginHistoryPo selectByLoginToken(@Param(\"loginToken\") String loginToken);\n\n int updateByPrimaryKeySelective(UserLoginHistoryPo record);\n\n int updateByPrimaryKey(UserLoginHistoryPo record);\n\n int updateIsValid(@Param(\"loginToken\") String loginToken, @Param(\"userId\") Long userId);\n}" }, { "identifier": "UserlistMapper", "path": "src/main/java/com/github/greatwqs/app/mapper/UserlistMapper.java", "snippet": "@Mapper\npublic interface UserlistMapper {\n int deleteByPrimaryKey(Long id);\n\n int insert(UserPo record);\n\n int insertSelective(UserPo record);\n\n UserPo selectByPrimaryKey(Long id);\n\n UserPo selectByUserName(@Param(\"username\") String username);\n\n List<UserPo> selectAllUsers();\n\n int updateByPrimaryKeySelective(UserPo record);\n\n int updateByPrimaryKey(UserPo record);\n}" }, { "identifier": "PublicUtils", "path": "src/main/java/com/github/greatwqs/app/utils/PublicUtils.java", "snippet": "public class PublicUtils {\n\n\t/***\n\t * getUuid, 36 char\n\t * @return\n\t */\n\tpublic static final String getUuid() {\n\t\treturn UUID.randomUUID().toString();\n\t}\n\n\t/****\n\t * getPageBeginIndex\n\t * @param pageNum The first pageNum is 1\n\t * @param pageSize\n\t * @return\n\t */\n\tpublic static final Integer getPageBeginIndex(Integer pageNum, Integer pageSize) {\n\t\treturn (pageNum - 1) * pageSize;\n\t}\n\n\t/***\n\t * get Total Page\n\t * @param totalRecordCount\n\t * @param onePageRecordSize\n\t * @return\n\t */\n\tpublic static final Integer getTotalPage(Integer totalRecordCount, Integer onePageRecordSize) {\n\t\treturn totalRecordCount / onePageRecordSize + ((totalRecordCount % onePageRecordSize == 0) ? 0 : 1);\n\t}\n\n\t/**\n\t * getClazzOrMethodAnnotation from HandlerMethod\n\t * 1. get annotation from class.\n\t * 2. get annotation from method.\n\t * @param handlerMethod\n\t * @param annotationClass\n\t * @param <T>\n\t * @return\n\t */\n\tpublic static <T extends Annotation> T getClazzOrMethodAnnotation(HandlerMethod handlerMethod,\n\t\tClass<T> annotationClass) {\n\t\tClass<?> clazz = handlerMethod.getBeanType();\n\t\tT annotation = clazz.getAnnotation(annotationClass);\n\t\tif (annotation != null) {\n\t\t\treturn annotation;\n\t\t}\n\n\t\treturn handlerMethod.getMethod().getAnnotation(annotationClass);\n\t}\n\n\tpublic static <T extends Annotation> T findClazzOrMethodAnnotation(HandlerMethod handlerMethod,\n\t\tClass<T> annotationClass) {\n\t\tClass<?> clazz = handlerMethod.getBeanType();\n\n\t\tT annotation = AnnotationUtils.findAnnotation(clazz, annotationClass);\n\t\tif (annotation != null) {\n\t\t\treturn annotation;\n\t\t}\n\n\t\treturn AnnotationUtils.findAnnotation(handlerMethod.getMethod(), annotationClass);\n\t}\n\n\t/***\n\t * isEnglishLetterOrNumber,\n\t * is all the cs param String in [A-Z] || [a-z] || [0-9]\n\t * @param cs\n\t * @return\n\t */\n\tpublic static boolean isEnglishLetterOrNumber(final CharSequence cs) {\n\t\tif (StringUtils.isEmpty(cs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal int length = cs.length();\n\t\tfor (int index = 0; index < length; index++) {\n\t\t\tif (isEnglishLetterOrNumber(cs.charAt(index)) == false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/***\n\t * isEnglishLetterOrNumber,\n\t * is the char in [A-Z] || [a-z] || [0-9]\n\t * @param letter\n\t * @return\n\t */\n\tprivate static boolean isEnglishLetterOrNumber(final char letter) {\n\t\tif (letter >= 48 && letter <= 57) {\n\t\t\treturn true; // 0-9\n\t\t}\n\t\treturn isEnglishLetter(letter);\n\t}\n\n\t/***\n\t * isEnglishLetter, is all the cs param String in [A-Z] || [a-z]\n\t * @param cs\n\t * @return\n\t */\n\tpublic static boolean isEnglishLetter(final CharSequence cs) {\n\t\tif (StringUtils.isEmpty(cs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal int length = cs.length();\n\t\tfor (int index = 0; index < length; index++) {\n\t\t\tif (isEnglishLetter(cs.charAt(index)) == false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/***\n\t * isEnglishLetter, is the char in [A-Z] || [a-z]\n\t * @param letter\n\t * @return\n\t */\n\tprivate static boolean isEnglishLetter(final char letter) {\n\t\tif (letter > 64 && letter < 91) {\n\t\t\treturn true;\n\t\t} else if (letter > 96 && letter < 123) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/***\n\t * get call class name\n\t * @return\n\t */\n\tpublic static String getClassName() {\n\t\tString classFulName = Thread.currentThread().getStackTrace()[2].getClassName();\n\t\tint dotIndex = classFulName.lastIndexOf(\".\");\n\t\treturn classFulName.substring(dotIndex + 1);\n\t}\n\n\t/***\n\t * get call method name\n\t * @return\n\t */\n\tpublic static String getMethodName() {\n\t\treturn Thread.currentThread().getStackTrace()[2].getMethodName();\n\t}\n\n}" }, { "identifier": "Lists", "path": "src/main/java/com/github/greatwqs/app/utils/collection/Lists.java", "snippet": "public final class Lists {\n\n\tprivate Lists() {\n\t}\n\n\t/***\n\t * isEmpty\n\t * @param list\n\t * @return\n\t */\n\tpublic static boolean isEmpty(Collection<?> list) {\n\t\treturn list == null || list.isEmpty();\n\t}\n\n\t/***\n\t * isNotEmpty\n\t * @param list\n\t * @return\n\t */\n\tpublic static boolean isNotEmpty(Collection<?> list) {\n\t\treturn !isEmpty(list);\n\t}\n\n\t/***\n\t * newArrayList\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> ArrayList<T> newArrayList(T... elements) {\n\t\treturn com.google.common.collect.Lists.newArrayList(elements);\n\t}\n\n\t/***\n\t * newLinkedList\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> LinkedList<T> newLinkedList(T... elements) {\n\t\tfinal LinkedList<T> linkedList = new LinkedList<T>();\n\t\tif (elements == null || elements.length == 0) {\n\t\t\treturn linkedList;\n\t\t}\n\t\tfor (final T t : elements) {\n\t\t\tlinkedList.add(t);\n\t\t}\n\t\treturn linkedList;\n\t}\n\n\t/***\n\t * newHashSet\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> HashSet<T> newHashSet(T... elements) {\n\t\treturn com.google.common.collect.Sets.newHashSet(elements);\n\t}\n\n\t/****\n\t * splitToInt\n\t * @param str\n\t * @param separator\n\t * @return\n\t */\n\tpublic static List<Integer> splitToInt(String str, String separator) {\n\t\tif (StringUtils.isBlank(str)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\tString[] parts = StringUtils.splitByWholeSeparator(str, separator);\n\t\tList<Integer> result = new ArrayList<Integer>(parts.length);\n\t\tfor (String num : parts) {\n\t\t\tif (NumberUtils.isDigits(num)) {\n\t\t\t\tresult.add(Integer.valueOf(num));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/***\n\t * removeNull\n\t * @param list\n\t */\n\tpublic static void removeNull(Collection<?> list) {\n\t\tif (isEmpty(list)) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Iterator<?> iterator = list.iterator(); iterator.hasNext(); ) {\n\t\t\tif (iterator.next() == null) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\t}\n\n\t/***\n\t * Collection size\n\t * @param list\n\t * @return\n\t */\n\tpublic static int size(Collection<?> list) {\n\t\treturn list == null ? 0 : list.size();\n\t}\n}" }, { "identifier": "UserPo", "path": "src/main/java/com/github/greatwqs/app/domain/po/UserPo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserPo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\tprivate String password;\n\n\tprivate String content;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}" }, { "identifier": "UserService", "path": "src/main/java/com/github/greatwqs/app/service/UserService.java", "snippet": "public interface UserService {\n\n\t/***\n\t * 用户登录, 登录成功返回LoginToken, 否则返回null\n\t * @param username\n\t * @param password\n\t * @return\n\t */\n\tString login(String username, String password, String loginIp);\n\n\t/**\n\t * 用户退出登录\n\t * @param userPo\n\t * @return\n\t */\n\tvoid logout(UserPo userPo, String loginToken);\n\n\t/***\n\t * 返回所有用户.\n\t * userPo 如果是超级用户, 返回所有的用户列表.\n\t * 如果是普通用户, 返回为空!\n\t * @param userPo\n\t * @return\n\t */\n\tList<UserVo> allUsers(UserPo userPo);\n\n\t/***\n\t * 用户添加, 返回创建的用户ID\n\t * @param username\n\t * @param content\n\t * @param userPo\n\t * @return\n\t */\n\tLong create(String username, String content, UserPo userPo);\n\n\t/**\n\t * 删除用户\n\t * @param deletedUserId 需要被删除的用户ID\n\t * @param userPo 当前登录管理员\n\t */\n\tvoid delete(Long deletedUserId, UserPo userPo);\n\n\t/***\n\t * 用户自己更新自己密码\n\t * @param userPo\n\t * @param oldPassword\n\t * @param newPassword\n\t * @param newPasswordConfirm\n\t */\n\tvoid updatePassword(UserPo userPo, String oldPassword, String newPassword, String newPasswordConfirm);\n}" }, { "identifier": "AppConstants", "path": "src/main/java/com/github/greatwqs/app/common/AppConstants.java", "snippet": "public class AppConstants {\n\n // default locale\n public static final Locale LOCALE = new Locale(\"zh\", \"CN\");\n\n /**\n * ErrorCode i18n properties prefix key.\n */\n public static final String ERROR_CODE_PREFIX_KEY = \"error.code.\";\n\n /**\n * request set attribute names\n * RequestContextHolder.currentRequestAttributes().setAttribute(name, value)\n */\n public static final String REQUEST_USER_TOKEN = \"requestUserToken\";\n public static final String REQUEST_USER = \"requestUser\";\n\n /***\n * 用户登录过期时间, 2小时.\n */\n public static final Long USER_LOGIN_SESSION_EXPIRE_TIME = 1000L * 60 * 60 * 2;\n\n /***\n * 分页时, 每页 Item 数量\n */\n public static final Integer DEFAULT_PAGE_SIZE = 50;\n // 订单每页 Item 数量\n public static final Integer ORDER_PAGE_SIZE = DEFAULT_PAGE_SIZE;\n\n /***\n * 用户密码最小/大位数\n */\n public static final Integer PASSWORD_MIN_LENGTH = 8;\n public static final Integer PASSWORD_MAX_LENGTH = 30;\n\n /***\n * 用户登录成功的cookie\n */\n public static final String COOKIE_LOGIN_TOKEN = \"loginToken\";\n public static final String APP_LOGIN_TOKEN = COOKIE_LOGIN_TOKEN;\n\n public static final String PAGE_LOGIN = \"/login.jsp\";\n public static final String PAGE_LOGIN_FAILED = \"/login_failed.jsp\";\n public static final String PAGE_ORDER_QUERY = \"/order_query\";\n public static final String PAGE_USER_ALL_LIST = \"/order_query?isHide=11\";\n public static final String PAGE_USER_UPDATE_PASSWORD = \"/order_query?isHide=1001\";\n}" } ]
import com.github.greatwqs.app.common.exception.AppException; import com.github.greatwqs.app.common.exception.ErrorCode; import com.github.greatwqs.app.domain.po.UserLoginHistoryPo; import com.github.greatwqs.app.domain.vo.UserVo; import com.github.greatwqs.app.manager.UserManager; import com.github.greatwqs.app.mapper.UserlistLoginHistoryMapper; import com.github.greatwqs.app.mapper.UserlistMapper; import com.github.greatwqs.app.utils.PublicUtils; import com.github.greatwqs.app.utils.collection.Lists; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.greatwqs.app.domain.po.UserPo; import com.github.greatwqs.app.service.UserService; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import static com.github.greatwqs.app.common.AppConstants.*;
5,122
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/6/25 */ @Slf4j @Service public class UserServiceImpl implements UserService { @Autowired private ModelMapper modelMapper; @Autowired private UserlistMapper userlistMapper; @Autowired private UserlistLoginHistoryMapper userlistLoginHistoryMapper; @Autowired private UserManager userManager; @Override @Transactional public String login(String username, String password, String loginIp) { UserPo userPo = this.userManager.getPoByName(username); if (userPo == null || !StringUtils.equals(userPo.getPassword(), password)) { log.warn("user login not ok, username: " + username + ", password: " + password); return StringUtils.EMPTY; } final String loginToken = PublicUtils.getUuid(); log.info("user login ok, username: " + username + ", password: " + password); this.insertLoginHistory(userPo, loginToken, loginIp); return loginToken; } private void insertLoginHistory(UserPo userPo, String loginToken, String loginIp) { UserLoginHistoryPo history = new UserLoginHistoryPo(); history.setId(null); history.setUserid(userPo.getId()); history.setLoginip(loginIp); history.setLogintoken(loginToken); history.setExpiretime(new Date(System.currentTimeMillis() + USER_LOGIN_SESSION_EXPIRE_TIME)); history.setIsvalid(true); history.setCreatetime(new Date()); history.setUpdatetime(new Date()); userlistLoginHistoryMapper.insertSelective(history); } @Override @Transactional public void logout(UserPo userPo, String loginToken) { userlistLoginHistoryMapper.updateIsValid(loginToken, userPo.getId()); } @Override public List<UserVo> allUsers(UserPo userPo) { if (!userPo.getIssuperadmin()) {
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/6/25 */ @Slf4j @Service public class UserServiceImpl implements UserService { @Autowired private ModelMapper modelMapper; @Autowired private UserlistMapper userlistMapper; @Autowired private UserlistLoginHistoryMapper userlistLoginHistoryMapper; @Autowired private UserManager userManager; @Override @Transactional public String login(String username, String password, String loginIp) { UserPo userPo = this.userManager.getPoByName(username); if (userPo == null || !StringUtils.equals(userPo.getPassword(), password)) { log.warn("user login not ok, username: " + username + ", password: " + password); return StringUtils.EMPTY; } final String loginToken = PublicUtils.getUuid(); log.info("user login ok, username: " + username + ", password: " + password); this.insertLoginHistory(userPo, loginToken, loginIp); return loginToken; } private void insertLoginHistory(UserPo userPo, String loginToken, String loginIp) { UserLoginHistoryPo history = new UserLoginHistoryPo(); history.setId(null); history.setUserid(userPo.getId()); history.setLoginip(loginIp); history.setLogintoken(loginToken); history.setExpiretime(new Date(System.currentTimeMillis() + USER_LOGIN_SESSION_EXPIRE_TIME)); history.setIsvalid(true); history.setCreatetime(new Date()); history.setUpdatetime(new Date()); userlistLoginHistoryMapper.insertSelective(history); } @Override @Transactional public void logout(UserPo userPo, String loginToken) { userlistLoginHistoryMapper.updateIsValid(loginToken, userPo.getId()); } @Override public List<UserVo> allUsers(UserPo userPo) { if (!userPo.getIssuperadmin()) {
return Lists.newLinkedList();
8
2023-10-16 12:45:57+00:00
8k
Wind-Gone/Vodka
code/src/main/java/utils/common/TableInfoCollector.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.query.baseQuery.orderOriginSize); // 通过查询获得的oorder表的实时大小\n public static AtomicLong orderLineTableSize = new AtomicLong(benchmark.olap.query.baseQuery.olOriginSize); // 通过查询获得的orderline表的实时大小\n public static AtomicLong orderlineTableNotNullSize = new AtomicLong(benchmark.olap.query.baseQuery.olNotnullSize);\n public static AtomicLong orderlineTableRecipDateNotNullSize = new AtomicLong(\n benchmark.olap.query.baseQuery.olNotnullSize);\n public static boolean filterRateCheck = false; // 为 TRUE 时获取过滤比分母查询\n public static boolean countPlan = false; // 为 TRUE 时记查询计划\n public static boolean detailedPlan = false; // 为 TRUE 以 json 格式保存查询计划\n private static final Logger log = Logger.getLogger(OLAPTerminal.class);\n private final OLTPClient parent;\n private final int interval;\n private final int dynamicParam;\n private final Connection conn;\n private final int dbType;\n private boolean stopRunningSignal = false;\n private String terminalName;\n private final String resultDirName;\n private static final int queryNumber = 22;\n private static final int planNumber = 2;\n private static final SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n private final String parallel_sql;\n private static final String origin_sql = \"set _force_parallel_query_dop = 1;\";\n private final boolean parallelSwitch;\n private static final String[] sqlPath = { \"tpchSQL/1.sql\", \"tpchSQL/2.sql\", \"tpchSQL/3.sql\", \"tpchSQL/4.sql\",\n \"tpchSQL/5.sql\",\n \"tpchSQL/6.sql\", \"tpchSQL/7.sql\", \"tpchSQL/8.sql\", \"tpchSQL/9.sql\", \"tpchSQL/10.sql\",\n \"tpchSQL/11.sql\", \"tpchSQL/12.sql\", \"tpchSQL/13.sql\", \"tpchSQL/14.sql\", \"tpchSQL/15.sql\",\n \"tpchSQL/16.sql\", \"tpchSQL/17.sql\", \"tpchSQL/18.sql\", \"tpchSQL/19.sql\", \"tpchSQL/20.sql\",\n \"tpchSQL/21.sql\", \"tpchSQL/22.sql\", \"tpchSQL/23.sql\" };\n\n private final TxnNumRecord txnNumRecord;\n\n public OLAPTerminal(String database, Properties dbProps, int dbType, int interval, OLTPClient parent,\n int dynamicParam, boolean parallelSwitch, int isolation_level, int parallel_degree, String iresultDirName)\n throws SQLException {\n this.dbType = dbType;\n this.resultDirName = iresultDirName;\n this.interval = interval;\n this.conn = DriverManager.getConnection(database, dbProps);\n this.conn.setAutoCommit(false);\n this.parent = parent;\n this.dynamicParam = dynamicParam;\n this.txnNumRecord = new TxnNumRecord(conn, dbType);\n this.parallelSwitch = parallelSwitch;\n this.parallel_sql = setQueryParalleDegreelByDBType(dbType, parallel_degree);\n isolation_level = 1; // default configuration\n switch (isolation_level) {\n case 0 -> conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);\n case 2 -> conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n case 3 -> conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);\n default -> conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);\n }\n }\n\n public static String setQueryParalleDegreelByDBType(int dbType, int parallel_degree) {\n String result = \"\";\n switch (dbType) {\n case CommonConfig.DB_OCEANBASE -> result = \"set _force_parallel_query_dop = \" + parallel_degree + \" ; \";\n case CommonConfig.DB_TIDB -> result = \"SET @@global.tidb_max_tiflash_threads = \" + parallel_degree + \" ; \";\n case CommonConfig.DB_POSTGRES ->\n result = \"SET max_parallel_workers_per_gather = \" + parallel_degree + \" ; \";\n case CommonConfig.DB_POLARDB -> result = \"set polar_px_dop_per_node = \" + parallel_degree + \" ; \";\n default -> log.error(\"vodka is not yet compatible with the database\");\n }\n return result;\n }\n\n @Override\n public void run() {\n try {\n log.info(\"AP Workloads Starting\");\n executeTPCHWorkload();\n log.info(\"AP execute end, pass end signal\");\n this.conn.close();\n } catch (IOException | SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n private void executeTPCHWorkload() throws IOException {\n PreparedStatement stmt, stmtCountCheck, stmtPlan, stmtJsonCheck;\n Statement paralleStmt;\n String[] queryName = new String[queryNumber];\n String[] filterRateLine = new String[queryNumber];\n String[] txnNum = new String[queryNumber];\n double[] lantency = new double[queryNumber];\n long[] queryStartTime = new long[queryNumber];\n ArrayList<String> queryPlan = new ArrayList<>();\n ArrayList<String> queryPlanJson = new ArrayList<>();\n boolean recordFileSignal = true;\n try {\n if (parallelSwitch) {\n if (dbType == CommonConfig.DB_TIDB || dbType == CommonConfig.DB_POSTGRES) { // set global parallel\n paralleStmt = conn.createStatement();\n paralleStmt.execute(parallel_sql);\n log.info(\"Executing parallel session sql for global\" + parallel_sql);\n paralleStmt.close();\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n // vector initialize\n Vector<baseQuery> queryVector = new Vector<>(queryNumber + 2);\n try {\n if (dynamicParam == 1) {\n String threadName = Thread.currentThread().getName();\n long startTime = System.nanoTime();\n int linearFitFunc;\n queryVector.clear();\n Q1 q1 = new Q1(dbType);\n queryVector.add(q1);\n Q2 q2 = new Q2(dbType);\n queryVector.add(q2);\n Q3 q3 = new Q3(dbType);\n queryVector.add(q3);\n Q4 q4 = new Q4(dbType);\n queryVector.add(q4);\n Q5 q5 = new Q5(dbType);\n queryVector.add(q5);\n Q6 q6 = new Q6(dbType);\n queryVector.add(q6);\n Q7 q7 = new Q7(dbType);\n queryVector.add(q7);\n Q8 q8 = new Q8(dbType);\n queryVector.add(q8);\n Q9 q9 = new Q9(dbType);\n queryVector.add(q9);\n Q10 q10 = new Q10(dbType);\n queryVector.add(q10);\n Q11 q11 = new Q11(dbType);\n queryVector.add(q11);\n Q12 q12 = new Q12(dbType);\n queryVector.add(q12);\n Q13 q13 = new Q13(dbType);\n queryVector.add(q13);\n Q14 q14 = new Q14(dbType);\n queryVector.add(q14);\n Q15 q15 = new Q15(dbType);\n queryVector.add(q15);\n Q16 q16 = new Q16(dbType);\n queryVector.add(q16);\n Q17 q17 = new Q17(dbType);\n queryVector.add(q17);\n Q18 q18 = new Q18(dbType);\n queryVector.add(q18);\n Q19 q19 = new Q19(dbType);\n queryVector.add(q19);\n Q20 q20 = new Q20(dbType);\n queryVector.add(q20);\n Q21 q21 = new Q21(dbType);\n queryVector.add(q21);\n Q22 q22 = new Q22(dbType);\n queryVector.add(q22);\n // Q23 q23 = new Q23(dbType);\n // queryVector.add(q23);\n\n while (!stopRunningSignal) {\n linearFitFunc = parent.linearFits();\n if (linearFitFunc == -1)\n continue;\n long currentLoopTime = System.nanoTime(); // 单位为ns\n if (Double.parseDouble(Long.toString(currentLoopTime - startTime)) / 1_000_000_000 > interval) { // s\n recordFileSignal = true;\n startTime = currentLoopTime;\n }\n\n File file1 = new File(resultDirName + \"/query.csv\"); // 存放数组数据的文件\n FileWriter out1;\n\n for (int i = 0; i < queryNumber; i++) {\n if (stopRunningSignal)\n break;\n queryName[i] = \"Vodka-AP-Query-\" + (i + 1);\n txnNum[i] = txnNumRecord.getCurrentTxnNum();\n baseQuery obj = queryVector.get(i);\n stmt = conn.prepareStatement(obj.updateQuery());\n\n out1 = new FileWriter(file1, true); // 文件写入流\n out1.write(\"query \" + (i + 1) + \":\" + obj.getQuery() + \"\\r\");\n // out1.write(\"query \"+(i+1)+\":\"+obj.getFilterCheckQuery() + \"\\r\");\n out1.close();\n\n stmtCountCheck = conn.prepareStatement(obj.getFilterCheckQuery());\n\n linearFitFunc = parent.linearFits();\n if (linearFitFunc == -1)\n log.error(\"fit failed in query \" + i);\n\n long startClick, endClick;\n // check query filter rate\n if (parallelSwitch && dbType == CommonConfig.DB_OCEANBASE) {\n paralleStmt = conn.createStatement(); // set session parallel\n paralleStmt.execute(parallel_sql);\n log.info(\"Executing parallel session sql for Q\" + (i + 1) + \" ,\" + parallel_sql);\n }\n\n startClick = System.currentTimeMillis();\n stmt.executeQuery();\n endClick = System.currentTimeMillis();\n double latency = Double.parseDouble(Long.toString(endClick - startClick));\n queryName[i] = sqlPath[i];\n queryStartTime[i] = startClick;\n lantency[i] = latency;\n // check query filter rate\n if (filterRateCheck && (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7\n || i == 9 || i == 11 || i == 13 || i == 19)) {\n // if (filterRateCheck && (i == 11)) {\n ResultSet rsCount1 = stmtCountCheck.executeQuery();\n while (rsCount1.next()) {\n if (dbType == CommonConfig.DB_OCEANBASE) {\n Object ors = rsCount1.getObject(1);\n filterRateLine[i] = ors + \", \" + OLAPClient.filterRate[i];\n } else if (dbType == CommonConfig.DB_POSTGRES) {\n Object ors = rsCount1.getObject(1);\n filterRateLine[i] = ors + \",\" + OLAPClient.filterRate[i];\n }\n }\n rsCount1.close();\n }\n\n // display query plan\n if (countPlan && ((i == 3) || (i == 19))) { // 这里指定显示哪些查询的计划\n stmtPlan = conn.prepareStatement(obj.getExplainQuery());\n ResultSet rsPlan = stmtPlan.executeQuery();\n while (rsPlan.next()) {\n System.out.println(rsPlan.getString(1));\n queryPlan.add(sdf.format(new java.util.Date()) + \"\\n\" + queryName[i]\n + \" query latency is: \" + lantency[i] + \" \\n \" + rsPlan.getString(1) + \"\\n\");\n }\n rsPlan.close();\n }\n // && (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7 || i ==\n // 9 || i == 11 || i == 13 || i == 19\n if (detailedPlan) {\n stmtJsonCheck = conn.prepareStatement(obj.getDetailedExecutionPlan());\n ResultSet rsPlan = stmtJsonCheck.executeQuery();\n if (rsPlan.next()) {\n queryPlanJson.add(queryName[i] + \" \\n \" + rsPlan.getString(1) + \"\\n\");\n }\n }\n\n if (recordFileSignal)\n log.info(sqlPath[i] + \"--\" + latency + \"ms\");\n }\n log.info(\"Complete a bunch of TPC-H queries\");\n\n if (recordFileSignal) {\n writeFile(queryName, queryStartTime, lantency, txnNum);\n if (detailedPlan)\n writePlanJsonToFile(queryPlanJson);\n if (filterRateCheck)\n writeLineCountCheckToFile(queryName, filterRateLine);\n if (countPlan)\n writePlanToFile(queryPlan);\n recordFileSignal = false;\n }\n log.info(\"check stopRunningSignal status: \" + stopRunningSignal);\n }\n }\n log.info(\"Quit AP threads running\");\n } catch (SQLException | IOException | ParseException | NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public void stopRunningWhenPossible() {\n stopRunningSignal = true;\n printMessage(\"Terminal received stop signal!\");\n printMessage(\"Finishing current transaction before exit...\");\n }\n\n public void writePlanToFile(ArrayList<String> queryPlan) throws IOException {\n File file = new File(resultDirName + \"/planResult-\" + dbType + \".csv\"); // 存放数组数据的文件\n FileWriter out = new FileWriter(file, true);\n for (String s : queryPlan)\n out.write(s);\n out.close();\n }\n\n public void writePlanJsonToFile(ArrayList<String> queryPlan) throws IOException {\n System.out.println(\"Write query plan in json layout to file.\");\n File file = new File(resultDirName + \"/planJsonResult-\" + dbType + \".csv\"); // 存放数组数据的文件\n FileWriter out = new FileWriter(file, true);\n out.write(sdf.format(new java.util.Date()) + \"\\n\");\n for (String s : queryPlan)\n out.write(s);\n out.write(\"orderline table size: \" + orderLineTableSize.intValue() + \", order table size: \"\n + oorderTableSize.intValue() + \", orderline not null size: \" + orderlineTableNotNullSize.intValue()\n + \"\\n\");\n out.close();\n }\n\n public void writeLineCountCheckToFile(String[] queryName, String[] linesCountCheck) throws IOException {\n System.out.println(\"Write selectivity to file.\");\n File file = new File(resultDirName + \"/lineCountResult-\" + dbType + \".csv\"); // 存放数组数据的文件\n FileWriter out = new FileWriter(file, true);\n for (int i = 0; i < queryNumber; i++)\n out.write((i + 1) + \",\" + queryName[i] + \",\" + linesCountCheck[i] + \",\" + \"countCheck\" + \"\\r\");\n out.close();\n }\n\n private void writeFile(String[] queryName, long[] queryStartTime, double[] lantency, String[] txnNum)\n throws IOException {\n log.info(\"write file\");\n File file = new File(resultDirName + \"/tpchresult-\" + dbType + \".csv\"); // 存放数组数据的文件\n FileWriter out = new FileWriter(file, true); // 文件写入流\n for (int i = 0; i < queryNumber; i++)\n out.write(longToDate(queryStartTime[i]) + \",\" + (i + 1) + \",\" + queryName[i] + \",\" + lantency[i] + \",\"\n + txnNum[i] + \"\\r\");\n out.close();\n }\n\n private void printMessage(String message) {\n log.trace(terminalName + \", \" + message);\n }\n\n public static String longToDate(long lo) {\n Date date = new Date(lo);\n SimpleDateFormat sd = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n return sd.format(date);\n }\n\n}" }, { "identifier": "CommonConfig", "path": "code/src/main/java/config/CommonConfig.java", "snippet": "public interface CommonConfig {\n String VdokaVersion = \"1.0 DEV\";\n\n int DB_UNKNOWN = 0,\n DB_FIREBIRD = 1,\n DB_ORACLE = 2,\n DB_POSTGRES = 3,\n DB_OCEANBASE = 4,\n DB_TIDB = 5,\n DB_POLARDB = 6,\n DB_GAUSSDB = 7,\n DB_MYSQL = 8;\n\n int NEW_ORDER = 1,\n PAYMENT = 2,\n ORDER_STATUS = 3,\n DELIVERY = 4,\n STOCK_LEVEL = 5,\n RECIEVE_GOODS = 6;\n\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\n}" } ]
import benchmark.olap.OLAPTerminal; import config.CommonConfig; import org.apache.log4j.Logger; import java.sql.*; import java.text.SimpleDateFormat; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong;
4,995
package utils.common; public class TableInfoCollector implements Runnable { private static org.apache.log4j.Logger log = Logger.getLogger(TableInfoCollector.class); int timeInterval; String sConn; Properties dbprop; Connection conn_tableStaticsCollect = null; int dbType; int sys_Tps_Limit; double neworderWeight; double paymentWeight; double deliveryWeight; double receiveGoodsWeight; SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //将毫秒级long值转换成日期格式 public TableInfoCollector(String iConn, Properties idbProps, int testTimeInterval, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) { this.sConn = iConn; this.dbprop = idbProps; this.timeInterval = testTimeInterval; this.dbType = dbType; this.sys_Tps_Limit = tps_limit; this.neworderWeight = ineworderWeight; this.paymentWeight = ipaymentWeight; this.deliveryWeight = ideliveryWeight; this.receiveGoodsWeight = ireceiveGoodsWeight; } public TableInfoCollector(String iConn, Properties dbProps, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) { this(iConn, dbProps, 5, dbType, tps_limit, ineworderWeight, ipaymentWeight, ideliveryWeight, ireceiveGoodsWeight); } @Override public void run() { // 执行信息收集任务的代码,定期收集两个表的数据 long startTimestamp = System.currentTimeMillis(); long currentTimestamp = startTimestamp; boolean systemNotStopRunning = true; // log.info("startTimestamp: " + dateformat.format(new Timestamp(startTimestamp).getTime())); // log.info("currentTimestamp: " + dateformat.format(new Timestamp(currentTimestamp).getTime())); try { long delta; do { // log.info("开始执行信息收集任务..."); conn_tableStaticsCollect = DriverManager.getConnection(sConn, dbprop); updateTableStaticsStatusLine(conn_tableStaticsCollect); conn_tableStaticsCollect.close(); // log.info("信息收集任务执行完成。开始更新状态信息。。"); startTimestamp = currentTimestamp; if (benchmark.oltp.OLTPClient.getSignalTerminalsRequestEndSent()) systemNotStopRunning = false; do { currentTimestamp = System.currentTimeMillis(); delta = currentTimestamp - startTimestamp; } while ((delta < 5000) && (systemNotStopRunning)); } while ((delta >= 5000) && (systemNotStopRunning)); } catch (SQLException e) { e.printStackTrace(); } } synchronized public void updateTableStaticsStatusLine(Connection dconn) throws SQLException { //may be can be changed int mode = 1; //mode=0 use select count table-real ,mode=1 use tps plus time count table-estimate if (mode == 0) { String sql1, sql2; if (dbType == CommonConfig.DB_TIDB) { sql1 = "SELECT /*+ read_from_storage(tiflash[vodka_oorder]) */ count(*) AS oorderTableSize FROM vodka_oorder"; sql2 = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ count(*) AS OrderlineTableSize FROM vodka_order_line"; } else { sql1 = "SELECT count(*) AS oorderTableSize FROM vodka_oorder"; sql2 = "SELECT count(*) AS OrderlineTableSize FROM vodka_order_line"; } PreparedStatement stmt1 = dconn.prepareStatement(sql1); ResultSet rs1 = stmt1.executeQuery(); if (!rs1.next()) throw new SQLException("get oorder table size error!");
package utils.common; public class TableInfoCollector implements Runnable { private static org.apache.log4j.Logger log = Logger.getLogger(TableInfoCollector.class); int timeInterval; String sConn; Properties dbprop; Connection conn_tableStaticsCollect = null; int dbType; int sys_Tps_Limit; double neworderWeight; double paymentWeight; double deliveryWeight; double receiveGoodsWeight; SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //将毫秒级long值转换成日期格式 public TableInfoCollector(String iConn, Properties idbProps, int testTimeInterval, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) { this.sConn = iConn; this.dbprop = idbProps; this.timeInterval = testTimeInterval; this.dbType = dbType; this.sys_Tps_Limit = tps_limit; this.neworderWeight = ineworderWeight; this.paymentWeight = ipaymentWeight; this.deliveryWeight = ideliveryWeight; this.receiveGoodsWeight = ireceiveGoodsWeight; } public TableInfoCollector(String iConn, Properties dbProps, int dbType, int tps_limit, double ineworderWeight, double ipaymentWeight, double ideliveryWeight, double ireceiveGoodsWeight) { this(iConn, dbProps, 5, dbType, tps_limit, ineworderWeight, ipaymentWeight, ideliveryWeight, ireceiveGoodsWeight); } @Override public void run() { // 执行信息收集任务的代码,定期收集两个表的数据 long startTimestamp = System.currentTimeMillis(); long currentTimestamp = startTimestamp; boolean systemNotStopRunning = true; // log.info("startTimestamp: " + dateformat.format(new Timestamp(startTimestamp).getTime())); // log.info("currentTimestamp: " + dateformat.format(new Timestamp(currentTimestamp).getTime())); try { long delta; do { // log.info("开始执行信息收集任务..."); conn_tableStaticsCollect = DriverManager.getConnection(sConn, dbprop); updateTableStaticsStatusLine(conn_tableStaticsCollect); conn_tableStaticsCollect.close(); // log.info("信息收集任务执行完成。开始更新状态信息。。"); startTimestamp = currentTimestamp; if (benchmark.oltp.OLTPClient.getSignalTerminalsRequestEndSent()) systemNotStopRunning = false; do { currentTimestamp = System.currentTimeMillis(); delta = currentTimestamp - startTimestamp; } while ((delta < 5000) && (systemNotStopRunning)); } while ((delta >= 5000) && (systemNotStopRunning)); } catch (SQLException e) { e.printStackTrace(); } } synchronized public void updateTableStaticsStatusLine(Connection dconn) throws SQLException { //may be can be changed int mode = 1; //mode=0 use select count table-real ,mode=1 use tps plus time count table-estimate if (mode == 0) { String sql1, sql2; if (dbType == CommonConfig.DB_TIDB) { sql1 = "SELECT /*+ read_from_storage(tiflash[vodka_oorder]) */ count(*) AS oorderTableSize FROM vodka_oorder"; sql2 = "SELECT /*+ read_from_storage(tiflash[vodka_order_line]) */ count(*) AS OrderlineTableSize FROM vodka_order_line"; } else { sql1 = "SELECT count(*) AS oorderTableSize FROM vodka_oorder"; sql2 = "SELECT count(*) AS OrderlineTableSize FROM vodka_order_line"; } PreparedStatement stmt1 = dconn.prepareStatement(sql1); ResultSet rs1 = stmt1.executeQuery(); if (!rs1.next()) throw new SQLException("get oorder table size error!");
OLAPTerminal.oorderTableSize = new AtomicLong(rs1.getInt("oorderTableSize"));
0
2023-10-22 11:22:32+00:00
8k
Onuraktasj/stock-tracking-system
src/main/java/com/onuraktas/stocktrackingsystem/impl/ProductServiceImpl.java
[ { "identifier": "ProductProducer", "path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/ProductProducer.java", "snippet": "@Component\npublic class ProductProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n public ProductProducer(RabbitTemplate rabbitTemplate) {\n this.rabbitTemplate = rabbitTemplate;\n }\n\n public <T> void sendToQueue(String queueName, T message) {\n rabbitTemplate.convertAndSend(queueName, message);\n }\n}" }, { "identifier": "QueueName", "path": "src/main/java/com/onuraktas/stocktrackingsystem/constant/QueueName.java", "snippet": "public class QueueName {\n\n public static final String DELETED_CATEGORY_QUEUE = \"deletedCategoryQueue\";\n public static final String DELETED_PRODUCT_QUEUE = \"deletedProductQueue\";\n}" }, { "identifier": "DeletedProductMessage", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/amqp/DeletedProductMessage.java", "snippet": "@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Builder\npublic class DeletedProductMessage implements Serializable {\n\n private UUID productId;\n}" }, { "identifier": "ProductDto", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/entity/ProductDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class ProductDto {\n\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n private Boolean isActive;\n}" }, { "identifier": "SimpleCategory", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/general/SimpleCategory.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class SimpleCategory {\n\n private UUID categoryId;\n}" }, { "identifier": "CreateProductRequest", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/CreateProductRequest.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CreateProductRequest {\n\n private String productName;\n private String description;\n private Integer amount;\n private List<SimpleCategory> categoryList;\n}" }, { "identifier": "UpdateProductAmountRequest", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/UpdateProductAmountRequest.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class UpdateProductAmountRequest {\n\n private Integer amount;\n}" }, { "identifier": "CreateProductResponse", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/CreateProductResponse.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@SuperBuilder\npublic class CreateProductResponse {\n\n private UUID productId;\n\n private String productName;\n\n private String status;\n}" }, { "identifier": "DeleteProductByIdResponse", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/DeleteProductByIdResponse.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class DeleteProductByIdResponse {\n\n private UUID productId;\n private Boolean isActive;\n}" }, { "identifier": "Category", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Category.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class Category {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID categoryId;\n private String categoryName;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "CategoryProductRel", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/CategoryProductRel.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class CategoryProductRel {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID id;\n private UUID categoryId;\n private UUID productId;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "Product", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Product.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode\n@Builder\n@ToString\n@Entity\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "Status", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/enums/Status.java", "snippet": "public enum Status {\n\n OK(\"OK\"),\n NOK(\"NOK\");\n\n private final String status;\n\n Status(String status){\n this.status = status;\n }\n\n public String getStatus(){\n return status;\n }\n}" }, { "identifier": "ProductBadRequestException", "path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/ProductBadRequestException.java", "snippet": "public class ProductBadRequestException extends RuntimeException {\n private String message;\n\n public ProductBadRequestException(String message) {\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}" }, { "identifier": "ProductNotFoundException", "path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/ProductNotFoundException.java", "snippet": "public class ProductNotFoundException extends RuntimeException{\n\n private final String message;\n\n public ProductNotFoundException(String message){\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}" }, { "identifier": "GeneralValues", "path": "src/main/java/com/onuraktas/stocktrackingsystem/helper/GeneralValues.java", "snippet": "public class GeneralValues {\n\n public static final Integer CATEGORY_MAX_SIZE = 3;\n}" }, { "identifier": "ProductMapper", "path": "src/main/java/com/onuraktas/stocktrackingsystem/mapper/ProductMapper.java", "snippet": "public class ProductMapper {\n\n public static ProductDto toDto(Product product){\n if (Objects.isNull(product))\n return null;\n return ProductDto.builder()\n .productId(product.getProductId())\n .productName(product.getProductName())\n .description(product.getDescription())\n .amount(product.getAmount())\n .isActive(product.getIsActive())\n .build();\n }\n\n public static Product toEntity(ProductDto productDto){\n if (Objects.isNull(productDto))\n return null;\n return Product.builder()\n .productId(productDto.getProductId())\n .productName(productDto.getProductName())\n .description(productDto.getDescription())\n .amount(productDto.getAmount())\n .build();\n }\n\n public static Product toEntity(CreateProductRequest createProductRequest){\n if (Objects.isNull(createProductRequest))\n return null;\n return Product.builder()\n .productName(createProductRequest.getProductName())\n .description(createProductRequest.getDescription())\n .amount(createProductRequest.getAmount())\n .build();\n }\n\n public static CreateProductResponse toCreateProductResponse(Product product){\n if (Objects.isNull(product))\n return null;\n\n return CreateProductResponse.builder()\n .productId(product.getProductId())\n .productName(product.getProductName())\n .build();\n }\n\n public static List<ProductDto> toDtoList(List<Product> products){\n return products.stream().parallel()\n .map(ProductMapper::toDto)\n .toList();\n }\n}" }, { "identifier": "ExceptionMessages", "path": "src/main/java/com/onuraktas/stocktrackingsystem/message/ExceptionMessages.java", "snippet": "public class ExceptionMessages {\n\n public static final String BAD_REQUEST = \"Bad request\";\n}" }, { "identifier": "ProductMessages", "path": "src/main/java/com/onuraktas/stocktrackingsystem/message/ProductMessages.java", "snippet": "public class ProductMessages {\n\n public static final String PRODUCT_NOT_FOUND = \"Product not found\";\n public static final String CATEGORY_LIST_EMPTY = \"Category list is empty\";\n public static final String CATEGORY_LIST_SIZE_EXCEEDED = \"Category list size exceeded\";\n public static final String CATEGORY_NOT_FOUND = \"Category not found\";\n}" }, { "identifier": "CategoryProductRelRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/CategoryProductRelRepository.java", "snippet": "@Repository\npublic interface CategoryProductRelRepository extends JpaRepository<CategoryProductRel, UUID> {\n\n List<CategoryProductRel> findAllByCategoryIdAndIsActive(UUID categoryId, Boolean isActive);\n List<CategoryProductRel> findAllByProductIdAndIsActive(UUID productId, Boolean isActive);\n List<CategoryProductRel> findAllByProductIdInAndIsActive(List<UUID> productIdList, Boolean isActive);\n}" }, { "identifier": "CategoryRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/CategoryRepository.java", "snippet": "public interface CategoryRepository extends JpaRepository<Category, UUID> {\n\n Optional<Category> findByCategoryIdAndIsActive(UUID categoryId, Boolean isActive);\n\n Category findByCategoryName(String categoryName);\n\n List<Category> findAllByCategoryIdInAndIsActive(List<UUID> categoryIds, Boolean isActive);\n}" }, { "identifier": "ProductRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/ProductRepository.java", "snippet": "public interface ProductRepository extends JpaRepository<Product, UUID> {\n\n List<Product> findAllByProductIdIn(List<UUID> productIdList);\n List<Product> findAllByProductIdInAndIsActive(List<UUID> productId, Boolean isActive);\n Optional<Product> findByProductIdAndIsActive(UUID productId, Boolean isActive);\n}" }, { "identifier": "ProductService", "path": "src/main/java/com/onuraktas/stocktrackingsystem/service/ProductService.java", "snippet": "public interface ProductService {\n\n CreateProductResponse createProduct(CreateProductRequest createProductRequest);\n List<ProductDto> getAllProduct();\n ProductDto getProduct(UUID productId);\n\n ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto);\n\n ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request);\n\n DeleteProductByIdResponse deleteProductById(UUID productId);\n\n List<ProductDto> getProductListByCategory(UUID categoryId);\n\n void deleteProductListByProductListIdList(List<UUID> productIdList);\n}" } ]
import com.onuraktas.stocktrackingsystem.amqp.producer.ProductProducer; import com.onuraktas.stocktrackingsystem.constant.QueueName; import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedProductMessage; import com.onuraktas.stocktrackingsystem.dto.entity.ProductDto; import com.onuraktas.stocktrackingsystem.dto.general.SimpleCategory; import com.onuraktas.stocktrackingsystem.dto.request.CreateProductRequest; import com.onuraktas.stocktrackingsystem.dto.request.UpdateProductAmountRequest; import com.onuraktas.stocktrackingsystem.dto.response.CreateProductResponse; import com.onuraktas.stocktrackingsystem.dto.response.DeleteProductByIdResponse; import com.onuraktas.stocktrackingsystem.entity.Category; import com.onuraktas.stocktrackingsystem.entity.CategoryProductRel; import com.onuraktas.stocktrackingsystem.entity.Product; import com.onuraktas.stocktrackingsystem.entity.enums.Status; import com.onuraktas.stocktrackingsystem.exception.ProductBadRequestException; import com.onuraktas.stocktrackingsystem.exception.ProductNotFoundException; import com.onuraktas.stocktrackingsystem.helper.GeneralValues; import com.onuraktas.stocktrackingsystem.mapper.ProductMapper; import com.onuraktas.stocktrackingsystem.message.ExceptionMessages; import com.onuraktas.stocktrackingsystem.message.ProductMessages; import com.onuraktas.stocktrackingsystem.repository.CategoryProductRelRepository; import com.onuraktas.stocktrackingsystem.repository.CategoryRepository; import com.onuraktas.stocktrackingsystem.repository.ProductRepository; import com.onuraktas.stocktrackingsystem.service.ProductService; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*;
3,870
package com.onuraktas.stocktrackingsystem.impl; @Service public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final CategoryProductRelRepository categoryProductRelRepository; private final CategoryRepository categoryRepository; private final ProductProducer productProducer; public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){ this.productRepository = productRepository; this.categoryProductRelRepository = categoryProductRelRepository; this.categoryRepository = categoryRepository; this.productProducer = productProducer; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CreateProductResponse createProduct(CreateProductRequest createProductRequest) { this.validateCreateProductRequest(createProductRequest); List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE); if (categoryList.isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND); List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList(); Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest)); CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product); createProductResponse.setStatus(Status.OK.getStatus()); List<CategoryProductRel> categoryProductRelList = new ArrayList<>(); for (UUID categoryId : categoryIdList) { categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build()); } this.categoryProductRelRepository.saveAll(categoryProductRelList); return createProductResponse; } @Override public List<ProductDto> getAllProduct() { return ProductMapper.toDtoList(productRepository.findAll()); } @Override public ProductDto getProduct(UUID productId) { return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND))); } @Override public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) { if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId())) return ResponseEntity.badRequest().build(); Optional<Product> existProduct = productRepository.findById(productId); if (existProduct.isEmpty()) return ResponseEntity.notFound().build(); final ProductDto updateProduct = this.save(productDto); if (Objects.nonNull(updateProduct)) return ResponseEntity.ok(updateProduct); return ResponseEntity.internalServerError().build(); } @Override public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) { Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)); product.setAmount(request.getAmount()); productRepository.save(product); return ProductMapper.toDto(productRepository.save(product)); } @Override public DeleteProductByIdResponse deleteProductById(UUID productId) { Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND)); deletedProduct.setIsActive(Boolean.FALSE); this.productRepository.save(deletedProduct); List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE); categoryProductRelList.forEach(categoryProductRel -> { categoryProductRel.setIsActive(Boolean.FALSE); }); this.categoryProductRelRepository.saveAll(categoryProductRelList); return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build(); } @Override public List<ProductDto> getProductListByCategory(UUID categoryId) { List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList(); if (productIdList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE)); if (productDtoList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); return productDtoList; } @Override public void deleteProductListByProductListIdList(List<UUID> productIdList) { List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE); productList.forEach(product -> product.setIsActive(Boolean.FALSE)); this.productRepository.saveAll(productList); List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>(); productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build())); this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList); } private ProductDto save (ProductDto productDto){ Product product = ProductMapper.toEntity(productDto); product = productRepository.save(product); return ProductMapper.toDto(product); } private void validateCreateProductRequest(CreateProductRequest createProductRequest) { if (Objects.isNull(createProductRequest)) throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST); if (Objects.isNull(createProductRequest.getCategoryList()) || createProductRequest.getCategoryList().isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_LIST_EMPTY);
package com.onuraktas.stocktrackingsystem.impl; @Service public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final CategoryProductRelRepository categoryProductRelRepository; private final CategoryRepository categoryRepository; private final ProductProducer productProducer; public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){ this.productRepository = productRepository; this.categoryProductRelRepository = categoryProductRelRepository; this.categoryRepository = categoryRepository; this.productProducer = productProducer; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CreateProductResponse createProduct(CreateProductRequest createProductRequest) { this.validateCreateProductRequest(createProductRequest); List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE); if (categoryList.isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND); List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList(); Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest)); CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product); createProductResponse.setStatus(Status.OK.getStatus()); List<CategoryProductRel> categoryProductRelList = new ArrayList<>(); for (UUID categoryId : categoryIdList) { categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build()); } this.categoryProductRelRepository.saveAll(categoryProductRelList); return createProductResponse; } @Override public List<ProductDto> getAllProduct() { return ProductMapper.toDtoList(productRepository.findAll()); } @Override public ProductDto getProduct(UUID productId) { return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND))); } @Override public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) { if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId())) return ResponseEntity.badRequest().build(); Optional<Product> existProduct = productRepository.findById(productId); if (existProduct.isEmpty()) return ResponseEntity.notFound().build(); final ProductDto updateProduct = this.save(productDto); if (Objects.nonNull(updateProduct)) return ResponseEntity.ok(updateProduct); return ResponseEntity.internalServerError().build(); } @Override public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) { Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)); product.setAmount(request.getAmount()); productRepository.save(product); return ProductMapper.toDto(productRepository.save(product)); } @Override public DeleteProductByIdResponse deleteProductById(UUID productId) { Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND)); deletedProduct.setIsActive(Boolean.FALSE); this.productRepository.save(deletedProduct); List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE); categoryProductRelList.forEach(categoryProductRel -> { categoryProductRel.setIsActive(Boolean.FALSE); }); this.categoryProductRelRepository.saveAll(categoryProductRelList); return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build(); } @Override public List<ProductDto> getProductListByCategory(UUID categoryId) { List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList(); if (productIdList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE)); if (productDtoList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); return productDtoList; } @Override public void deleteProductListByProductListIdList(List<UUID> productIdList) { List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE); productList.forEach(product -> product.setIsActive(Boolean.FALSE)); this.productRepository.saveAll(productList); List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>(); productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build())); this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList); } private ProductDto save (ProductDto productDto){ Product product = ProductMapper.toEntity(productDto); product = productRepository.save(product); return ProductMapper.toDto(product); } private void validateCreateProductRequest(CreateProductRequest createProductRequest) { if (Objects.isNull(createProductRequest)) throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST); if (Objects.isNull(createProductRequest.getCategoryList()) || createProductRequest.getCategoryList().isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_LIST_EMPTY);
if (createProductRequest.getCategoryList().size() > GeneralValues.CATEGORY_MAX_SIZE)
15
2023-10-23 19:00:09+00:00
8k
ushh789/FinancialCalculator
src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/OpenFile.java
[ { "identifier": "Credit", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java", "snippet": "public class Credit implements Savable {\n protected float loan;\n protected String currency;\n protected float annualPercent;\n protected LocalDate startDate;\n protected LocalDate endDate;\n protected int paymentType;\n protected int contractDuration;\n\n public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {\n this.loan = loan;\n this.currency = currency;\n this.annualPercent = annualPercent;\n this.startDate = startDate;\n this.endDate = endDate;\n this.paymentType = paymentType;\n this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate);\n }\n\n public float countLoan() {\n return loan * (1f / 365f) * (annualPercent / 100f);\n }\n\n public float countCreditBodyPerDay(){\n return loan/contractDuration;\n }\n\n\n public void save() {\n Gson gson = new GsonBuilder()\n .setPrettyPrinting()\n .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())\n .create();\n JsonObject jsonObject = getJsonObject();\n String json = gson.toJson(jsonObject);\n\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(LanguageManager.getInstance().getStringBinding(\"saveButton\").get());\n File initialDirectory = new File(\"saves/\");\n fileChooser.setInitialDirectory(initialDirectory);\n fileChooser.getExtensionFilters().addAll(\n new FileChooser.ExtensionFilter(\"JSON Files\", \"*.json\"));\n File file = fileChooser.showSaveDialog(null);\n\n if (file != null) {\n try (FileWriter writer = new FileWriter(file)) {\n writer.write(json);\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error while saving Credit to json\", e);\n }\n }\n }\n\n public void sendCreditToResultTable() {\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"/com/netrunners/financialcalculator/ResultTable.fxml\"));\n try {\n Parent root = loader.load();\n ResultTableController resultTableController = loader.getController();\n resultTableController.updateTable(this);\n\n Stage stage = new Stage();\n stage.setTitle(LanguageManager.getInstance().getStringBinding(\"ResultTableLabel\").get());\n Scene scene = new Scene(root);\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(720);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error while sending Credit to result table\", e);\n }\n }\n\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"loan\", this.loan);\n jsonObject.addProperty(\"annualPercent\", this.annualPercent);\n jsonObject.addProperty(\"currency\", this.currency);\n jsonObject.addProperty(\"paymentType\", this.paymentType);\n jsonObject.addProperty(\"startDate\", this.startDate.toString());\n jsonObject.addProperty(\"endDate\", this.endDate.toString());\n return jsonObject;\n }\n\n public float getLoan() {\n return loan;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public float getAnnualPercent() {\n return annualPercent;\n }\n\n public LocalDate getStartDate() {\n return startDate;\n }\n\n public LocalDate getEndDate() {\n return endDate;\n }\n\n public int getPaymentType() {\n return paymentType;\n }\n\n public void setLoan(float loan) {\n this.loan = loan;\n }\n\n public String getNameOfPaymentType() {\n LanguageManager languageManager = LanguageManager.getInstance();\n switch (paymentType) {\n case 1 -> {\n return \"Months\";\n }\n case 2 -> {\n return \"Quarters\";\n }\n case 3 -> {\n return \"Years\";\n }\n case 4 -> {\n return \"EndofTerm\";\n }\n }\n return languageManager.getStringBinding(\"None\").get();\n }\n}" }, { "identifier": "CreditWithHolidays", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/CreditWithHolidays.java", "snippet": "public class CreditWithHolidays extends Credit{\n private final LocalDate holidaysStart;\n private final LocalDate holidaysEnd;\n\n public CreditWithHolidays(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType, LocalDate holidaysStart, LocalDate holidaysEnd) {\n super(loan, currency, annualPercent, startDate, endDate, paymentType);\n this.holidaysStart = holidaysStart;\n this.holidaysEnd = holidaysEnd;\n }\n\n @Override\n public float countLoan() {\n return super.countLoan();\n }\n\n @Override\n public float countCreditBodyPerDay() {\n return loan / (this.contractDuration - this.countHolidaysDuration());\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n @Override\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Credit\");\n jsonObject.addProperty(\"type\", \"WithHolidays\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n jsonObject.addProperty(\"holidaysStart\", holidaysStart.toString());\n jsonObject.addProperty(\"holidaysEnd\", holidaysEnd.toString());\n return jsonObject;\n }\n\n public LocalDate getHolidaysStart() {\n return holidaysStart;\n }\n\n public LocalDate getHolidaysEnd() {\n return holidaysEnd;\n }\n\n public int countHolidaysDuration() {\n return DateTimeFunctions.countDaysBetweenDates(holidaysStart, holidaysEnd);\n }\n\n}" }, { "identifier": "CreditWithoutHolidays", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/CreditWithoutHolidays.java", "snippet": "public class CreditWithoutHolidays extends Credit{\n\n public CreditWithoutHolidays(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {\n super(loan, currency, annualPercent, startDate, endDate, paymentType);\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n @Override\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Credit\");\n jsonObject.addProperty(\"type\", \"WithoutHolidays\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n return jsonObject;\n }\n\n}" }, { "identifier": "CapitalisedDeposit", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Deposit/CapitalisedDeposit.java", "snippet": "public class CapitalisedDeposit extends Deposit {\n public CapitalisedDeposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, LocalDate earlyWithdrawalDate, int withdrawalOption) {\n super(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, earlyWithdrawalDate, withdrawalOption);\n }\n\n public CapitalisedDeposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, int withdrawalOption) {\n super(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, withdrawalOption);\n }\n\n @Override\n public float countProfit() {\n return super.countProfit();\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Deposit\");\n jsonObject.addProperty(\"type\", \"Capitalized\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n return jsonObject;\n }\n\n}" }, { "identifier": "Deposit", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Deposit/Deposit.java", "snippet": "public abstract class Deposit implements Savable {\n protected float investment;\n protected float annualPercent;\n protected String currency;\n protected LocalDate startDate;\n protected LocalDate endDate;\n protected int withdrawalOption;\n protected boolean earlyWithdrawal;\n protected LocalDate earlyWithdrawalDate;\n\n\n public float countProfit() {\n return investment * (1f / 365f) * (annualPercent / 100f);\n }\n\n public Deposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, LocalDate earlyWithdrawalDate, int withdrawalOption) {\n this.investment = investment;\n this.currency = currency;\n this.annualPercent = annualPercent;\n this.startDate = startDate;\n this.endDate = endDate;\n this.earlyWithdrawal = earlyWithdrawal;\n this.earlyWithdrawalDate = earlyWithdrawalDate;\n this.withdrawalOption = withdrawalOption;\n }\n\n public Deposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, int withdrawalOption) {\n this.investment = investment;\n this.currency = currency;\n this.annualPercent = annualPercent;\n this.startDate = startDate;\n this.endDate = endDate;\n this.earlyWithdrawal = earlyWithdrawal;\n this.withdrawalOption = withdrawalOption;\n }\n\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"investment\", this.investment);\n jsonObject.addProperty(\"annualPercent\", this.annualPercent);\n jsonObject.addProperty(\"currency\", this.currency);\n jsonObject.addProperty(\"startDate\", this.startDate.toString());\n jsonObject.addProperty(\"endDate\", this.endDate.toString());\n jsonObject.addProperty(\"withdrawalOption\", this.withdrawalOption);\n if (this.earlyWithdrawal) {\n jsonObject.addProperty(\"earlyWithdrawalDate\", this.earlyWithdrawalDate.toString());\n } else {\n jsonObject.addProperty(\"earlyWithdrawalDate\", \"None\");\n }\n jsonObject.addProperty(\"earlyWithdrawal\", this.earlyWithdrawal);\n return jsonObject;\n }\n\n @Override\n public void save() {\n Gson gson = new GsonBuilder()\n .setPrettyPrinting()\n .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())\n .create();\n JsonObject jsonObject = getJsonObject();\n String json = gson.toJson(jsonObject);\n\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(LanguageManager.getInstance().getStringBinding(\"saveButton\").get());\n File initialDirectory = new File(\"saves/\");\n fileChooser.setInitialDirectory(initialDirectory);\n fileChooser.getExtensionFilters().addAll(\n new FileChooser.ExtensionFilter(\"JSON Files\", \"*.json\"));\n File file = fileChooser.showSaveDialog(null);\n\n if(file != null){\n try {\n FileWriter fileWriter = new FileWriter(file);\n fileWriter.write(json);\n fileWriter.close();\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error while saving Deposit to json\", e);\n }\n }\n }\n\n public void sendDepositToResultTable() {\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"/com/netrunners/financialcalculator/ResultTable.fxml\"));\n try {\n Parent root = loader.load();\n ResultTableController resultTableController = loader.getController();\n resultTableController.updateTable(this);\n\n Stage stage = new Stage();\n stage.setTitle(LanguageManager.getInstance().getStringBinding(\"ResultTableLabel\").get());\n Scene scene = new Scene(root);\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(720);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error while sending Deposit to result table\", e);\n }\n }\n\n public String getNameOfWithdrawalType() {\n LanguageManager languageManager = LanguageManager.getInstance();\n switch (withdrawalOption) {\n case 1 -> {\n return \"Months\";\n }\n case 2 -> {\n return \"Quarters\";\n }\n case 3 -> {\n return \"Years\";\n }\n case 4 -> {\n return \"EndofTerm\";\n }\n }\n return languageManager.getStringBinding(\"None\").get();\n }\n\n\n\n\n public float getInvestment() {\n return investment;\n }\n\n public void setInvestment(float investment) {\n this.investment = investment;\n }\n\n public float getAnnualPercent() {\n return annualPercent;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public LocalDate getStartDate() {\n return startDate;\n }\n\n public LocalDate getEndDate() {\n return endDate;\n }\n\n public int getWithdrawalOption() {\n return withdrawalOption;\n }\n\n public boolean isEarlyWithdrawal() {\n return earlyWithdrawal;\n }\n\n public LocalDate getEarlyWithdrawalDate() {\n return earlyWithdrawalDate;\n }\n}" }, { "identifier": "UncapitalisedDeposit", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Deposit/UncapitalisedDeposit.java", "snippet": "public class UncapitalisedDeposit extends Deposit {\n public UncapitalisedDeposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, LocalDate earlyWithdrawalDate, int withdrawalOption) {\n super(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, earlyWithdrawalDate, withdrawalOption);\n }\n\n public UncapitalisedDeposit(float investment, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, boolean earlyWithdrawal, int withdrawalOption) {\n super(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, withdrawalOption);\n }\n\n @Override\n public float countProfit() {\n return super.countProfit();\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Deposit\");\n jsonObject.addProperty(\"type\", \"Uncapitalized\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n return jsonObject;\n }\n}" }, { "identifier": "LanguageManager", "path": "src/main/java/com/netrunners/financialcalculator/VisualInstruments/MenuActions/LanguageManager.java", "snippet": "public class LanguageManager {\n private static LanguageManager instance;\n private ObservableResourceFactory resourceFactory;\n private Properties properties;\n private static final String PROPERTIES_FILE = \"config.properties\";\n\n\n private LanguageManager() {\n resourceFactory = new ObservableResourceFactory();\n properties = new Properties();\n loadLanguage();\n }\n public Locale getLocale() {\n return resourceFactory.getResources().getLocale();\n }\n\n public static LanguageManager getInstance() {\n if (instance == null) {\n instance = new LanguageManager();\n }\n return instance;\n }\n private void loadLanguage() {\n try (InputStream input = new FileInputStream(PROPERTIES_FILE)) {\n properties.load(input);\n if (properties.getProperty(\"language\") != null) {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", new Locale(properties.getProperty(\"language\"))));\n } else {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", new Locale(\"en\")));\n }\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n public void saveLanguage() {\n try (OutputStream output = new FileOutputStream(PROPERTIES_FILE)) {\n properties.setProperty(\"language\", resourceFactory.getResources().getLocale().getLanguage());\n properties.store(output, null);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n public void changeLanguage(Locale locale) {\n resourceFactory.setResources(ResourceBundle.getBundle(\"com/netrunners/financialcalculator/assets/messages\", locale));\n }\n\n public StringBinding getStringBinding(String key) {\n return resourceFactory.getStringBinding(key);\n }\n\n public static int checkOption(String chosenOption){\n LanguageManager languageManager = LanguageManager.getInstance();\n String option1 = languageManager.getStringBinding(\"Option1\").get();\n String option2 = languageManager.getStringBinding(\"Option2\").get();\n String option3 = languageManager.getStringBinding(\"Option3\").get();\n String option4 = languageManager.getStringBinding(\"Option4\").get();\n\n if (chosenOption.equals(option1)) {\n return 1;\n } else if (chosenOption.equals(option2)) {\n return 2;\n } else if (chosenOption.equals(option3)) {\n return 3;\n } else if (chosenOption.equals(option4)) {\n return 4;\n } else {\n return -1000;\n }\n }\n}" }, { "identifier": "startMenuScene", "path": "src/main/java/com/netrunners/financialcalculator/StartMenu.java", "snippet": "public static Scene startMenuScene;" } ]
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.Credit; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithHolidays; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithoutHolidays; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.CapitalisedDeposit; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.Deposit; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.UncapitalisedDeposit; import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager; import javafx.scene.image.Image; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.time.LocalDate; import java.util.logging.Level; import static com.netrunners.financialcalculator.StartMenu.startMenuScene;
4,950
package com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments; public class OpenFile { public static void openFromSave() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("ChooseOpenFile").get()); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json")); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { try (FileReader reader = new FileReader(selectedFile)) { Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); String operationType = jsonObject.get("operation").getAsString(); switch (operationType) { case "Credit" -> { Credit credit = createCredit(jsonObject); credit.sendCreditToResultTable(); } case "Deposit" -> { Deposit deposit = createDeposit(jsonObject); deposit.sendDepositToResultTable(); } default -> LogHelper.log(Level.WARNING, "Can't open file with operation type: " + operationType, null); } } catch (IOException | JsonParseException e) { LogHelper.log(Level.SEVERE, "Error while opening file", e); } } } private static Credit createCredit(JsonObject jsonObject) { Credit credit = null; try { float loan = jsonObject.get("loan").getAsFloat(); float annualPercent = jsonObject.get("annualPercent").getAsFloat(); int paymentType = jsonObject.get("paymentType").getAsInt(); String currency = jsonObject.get("currency").getAsString(); String startDateString = jsonObject.get("startDate").getAsString(); LocalDate startDate = LocalDate.parse(startDateString); String endDateString = jsonObject.get("endDate").getAsString(); LocalDate endDate = LocalDate.parse(endDateString); if (jsonObject.get("type").getAsString().equals("WithHolidays")) { String holidaysStartString = jsonObject.get("holidaysStart").getAsString(); LocalDate holidaysStart = LocalDate.parse(holidaysStartString); String holidaysEndString = jsonObject.get("holidaysEnd").getAsString(); LocalDate holidaysEnd = LocalDate.parse(holidaysEndString);
package com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments; public class OpenFile { public static void openFromSave() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("ChooseOpenFile").get()); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON files (*.json)", "*.json")); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { try (FileReader reader = new FileReader(selectedFile)) { Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); String operationType = jsonObject.get("operation").getAsString(); switch (operationType) { case "Credit" -> { Credit credit = createCredit(jsonObject); credit.sendCreditToResultTable(); } case "Deposit" -> { Deposit deposit = createDeposit(jsonObject); deposit.sendDepositToResultTable(); } default -> LogHelper.log(Level.WARNING, "Can't open file with operation type: " + operationType, null); } } catch (IOException | JsonParseException e) { LogHelper.log(Level.SEVERE, "Error while opening file", e); } } } private static Credit createCredit(JsonObject jsonObject) { Credit credit = null; try { float loan = jsonObject.get("loan").getAsFloat(); float annualPercent = jsonObject.get("annualPercent").getAsFloat(); int paymentType = jsonObject.get("paymentType").getAsInt(); String currency = jsonObject.get("currency").getAsString(); String startDateString = jsonObject.get("startDate").getAsString(); LocalDate startDate = LocalDate.parse(startDateString); String endDateString = jsonObject.get("endDate").getAsString(); LocalDate endDate = LocalDate.parse(endDateString); if (jsonObject.get("type").getAsString().equals("WithHolidays")) { String holidaysStartString = jsonObject.get("holidaysStart").getAsString(); LocalDate holidaysStart = LocalDate.parse(holidaysStartString); String holidaysEndString = jsonObject.get("holidaysEnd").getAsString(); LocalDate holidaysEnd = LocalDate.parse(holidaysEndString);
credit = new CreditWithHolidays(loan, currency, annualPercent, startDate, endDate, paymentType, holidaysStart, holidaysEnd);
1
2023-10-18 16:03:09+00:00
8k
bowbahdoe/java-audio-stack
mp3spi/src/main/java/dev/mccue/mp3spi/mpeg/sampled/convert/MpegFormatConversionProvider.java
[ { "identifier": "TDebug", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/TDebug.java", "snippet": "public class TDebug\r\n{\r\n\tpublic static boolean\t\tSHOW_ACCESS_CONTROL_EXCEPTIONS = false;\r\n\tprivate static final String\tPROPERTY_PREFIX = \"tritonus.\";\r\n\t// The stream we output to\r\n\tpublic static PrintStream\tm_printStream = System.out;\r\n\r\n\tprivate static String indent=\"\";\r\n\r\n\t// meta-general\r\n\tpublic static boolean\tTraceAllExceptions = getBooleanProperty(\"TraceAllExceptions\");\r\n\tpublic static boolean\tTraceAllWarnings = getBooleanProperty(\"TraceAllWarnings\");\r\n\r\n\t// general\r\n\tpublic static boolean\tTraceInit = getBooleanProperty(\"TraceInit\");\r\n\tpublic static boolean\tTraceCircularBuffer = getBooleanProperty(\"TraceCircularBuffer\");\r\n\tpublic static boolean\tTraceService = getBooleanProperty(\"TraceService\");\r\n\r\n\t// sampled common implementation\r\n\tpublic static boolean\tTraceAudioSystem = getBooleanProperty(\"TraceAudioSystem\");\r\n\tpublic static boolean\tTraceAudioConfig = getBooleanProperty(\"TraceAudioConfig\");\r\n\tpublic static boolean\tTraceAudioInputStream = getBooleanProperty(\"TraceAudioInputStream\");\r\n\tpublic static boolean\tTraceMixerProvider = getBooleanProperty(\"TraceMixerProvider\");\r\n\tpublic static boolean\tTraceControl = getBooleanProperty(\"TraceControl\");\r\n\tpublic static boolean\tTraceLine = getBooleanProperty(\"TraceLine\");\r\n\tpublic static boolean\tTraceDataLine = getBooleanProperty(\"TraceDataLine\");\r\n\tpublic static boolean\tTraceMixer = getBooleanProperty(\"TraceMixer\");\r\n\tpublic static boolean\tTraceSourceDataLine = getBooleanProperty(\"TraceSourceDataLine\");\r\n\tpublic static boolean\tTraceTargetDataLine = getBooleanProperty(\"TraceTargetDataLine\");\r\n\tpublic static boolean\tTraceClip = getBooleanProperty(\"TraceClip\");\r\n\tpublic static boolean\tTraceAudioFileReader = getBooleanProperty(\"TraceAudioFileReader\");\r\n\tpublic static boolean\tTraceAudioFileWriter = getBooleanProperty(\"TraceAudioFileWriter\");\r\n\tpublic static boolean\tTraceAudioConverter = getBooleanProperty(\"TraceAudioConverter\");\r\n\tpublic static boolean\tTraceAudioOutputStream = getBooleanProperty(\"TraceAudioOutputStream\");\r\n\r\n\t// sampled specific implementation\r\n\tpublic static boolean\tTraceEsdNative = getBooleanProperty(\"TraceEsdNative\");\r\n\tpublic static boolean\tTraceEsdStreamNative = getBooleanProperty(\"TraceEsdStreamNative\");\r\n\tpublic static boolean\tTraceEsdRecordingStreamNative = getBooleanProperty(\"TraceEsdRecordingStreamNative\");\r\n\tpublic static boolean\tTraceAlsaNative = getBooleanProperty(\"TraceAlsaNative\");\r\n\tpublic static boolean\tTraceAlsaMixerNative = getBooleanProperty(\"TraceAlsaMixerNative\");\r\n\tpublic static boolean\tTraceAlsaPcmNative = getBooleanProperty(\"TraceAlsaPcmNative\");\r\n\tpublic static boolean\tTraceMixingAudioInputStream = getBooleanProperty(\"TraceMixingAudioInputStream\");\r\n\tpublic static boolean\tTraceOggNative = getBooleanProperty(\"TraceOggNative\");\r\n\tpublic static boolean\tTraceVorbisNative = getBooleanProperty(\"TraceVorbisNative\");\r\n\r\n\t// midi common implementation\r\n\tpublic static boolean\tTraceMidiSystem = getBooleanProperty(\"TraceMidiSystem\");\r\n\tpublic static boolean\tTraceMidiConfig = getBooleanProperty(\"TraceMidiConfig\");\r\n\tpublic static boolean\tTraceMidiDeviceProvider = getBooleanProperty(\"TraceMidiDeviceProvider\");\r\n\tpublic static boolean\tTraceSequencer = getBooleanProperty(\"TraceSequencer\");\r\n\tpublic static boolean\tTraceSynthesizer = getBooleanProperty(\"TraceSynthesizer\");\r\n\tpublic static boolean\tTraceMidiDevice = getBooleanProperty(\"TraceMidiDevice\");\r\n\r\n\t// midi specific implementation\r\n\tpublic static boolean\tTraceAlsaSeq = getBooleanProperty(\"TraceAlsaSeq\");\r\n\tpublic static boolean\tTraceAlsaSeqDetails = getBooleanProperty(\"TraceAlsaSeqDetails\");\r\n\tpublic static boolean\tTraceAlsaSeqNative = getBooleanProperty(\"TraceAlsaSeqNative\");\r\n\tpublic static boolean\tTracePortScan = getBooleanProperty(\"TracePortScan\");\r\n\tpublic static boolean\tTraceAlsaMidiIn = getBooleanProperty(\"TraceAlsaMidiIn\");\r\n\tpublic static boolean\tTraceAlsaMidiOut = getBooleanProperty(\"TraceAlsaMidiOut\");\r\n\tpublic static boolean\tTraceAlsaMidiChannel = getBooleanProperty(\"TraceAlsaMidiChannel\");\r\n\r\n\tpublic static boolean\tTraceFluidNative = getBooleanProperty(\"TraceFluidNative\");\r\n\r\n\t// misc\r\n\tpublic static boolean\tTraceAlsaCtlNative = getBooleanProperty(\"TraceAlsaCtlNative\");\r\n\tpublic static boolean\tTraceCdda = getBooleanProperty(\"TraceCdda\");\r\n\tpublic static boolean\tTraceCddaNative = getBooleanProperty(\"TraceCddaNative\");\r\n\r\n\r\n\r\n\t// make this method configurable to write to file, write to stderr,...\r\n\tpublic static void out(String strMessage)\r\n\t{\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='<') {\r\n\t\t\tif (indent.length()>2) {\t\r\n\t\t\t\tindent=indent.substring(2);\r\n\t\t\t} else {\r\n\t\t\t\tindent=\"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tString newMsg=null;\r\n\t\tif (indent!=\"\" && strMessage.indexOf(\"\\n\")>=0) {\r\n\t\t\tnewMsg=\"\";\r\n\t\t\tStringTokenizer tokenizer=new StringTokenizer(strMessage, \"\\n\");\r\n\t\t\twhile (tokenizer.hasMoreTokens()) {\r\n\t\t\t\tnewMsg+=indent+tokenizer.nextToken()+\"\\n\";\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tnewMsg=indent+strMessage;\r\n\t\t}\r\n\t\tm_printStream.println(newMsg);\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='>') {\r\n\t\t\t\tindent+=\" \";\r\n\t\t} \r\n\t}\r\n\r\n\r\n\r\n\tpublic static void out(Throwable throwable)\r\n\t{\r\n\t\tthrowable.printStackTrace(m_printStream);\r\n\t}\r\n\r\n\r\n\r\n\tpublic static void assertion(boolean bAssertion)\r\n\t{\r\n\t\tif (!bAssertion)\r\n\t\t{\r\n\t\t\tthrow new AssertException();\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tpublic static class AssertException\r\n\textends RuntimeException\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 1;\r\n\r\n\t\tpublic AssertException()\r\n\t\t{\r\n\t\t}\r\n\r\n\r\n\r\n\t\tpublic AssertException(String sMessage)\r\n\t\t{\r\n\t\t\tsuper(sMessage);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate static boolean getBooleanProperty(String strName)\r\n\t{\r\n\t\tString\tstrPropertyName = PROPERTY_PREFIX + strName;\r\n\t\tString\tstrValue = \"false\";\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstrValue = System.getProperty(strPropertyName, \"false\");\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tif (SHOW_ACCESS_CONTROL_EXCEPTIONS)\r\n\t\t\t{\r\n\t\t\t\tout(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\t// TDebug.out(\"property: \" + strPropertyName + \"=\" + strValue);\r\n\t\tboolean\tbValue = strValue.toLowerCase().equals(\"true\");\r\n\t\t// TDebug.out(\"bValue: \" + bValue);\r\n\t\treturn bValue;\r\n\t}\r\n}\r" }, { "identifier": "Encodings", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/Encodings.java", "snippet": "public class Encodings extends AudioFormat.Encoding {\r\n\r\n\t/** contains all known encodings */\r\n\tprivate static StringHashedSet<AudioFormat.Encoding> encodings = new StringHashedSet<AudioFormat.Encoding>();\r\n\r\n\t// initially add the standard encodings\r\n\tstatic {\r\n\t\tencodings.add(AudioFormat.Encoding.PCM_SIGNED);\r\n\t\tencodings.add(AudioFormat.Encoding.PCM_UNSIGNED);\r\n\t\tencodings.add(AudioFormat.Encoding.ULAW);\r\n\t\tencodings.add(AudioFormat.Encoding.ALAW);\r\n\t}\r\n\r\n\tEncodings(String name) {\r\n\t\tsuper(name);\r\n\t}\r\n\r\n\t/**\r\n\t * Use this method for retrieving an instance of\r\n\t * <code>AudioFormat.Encoding</code> of the specified\r\n\t * name. A standard registry of encoding names will\r\n\t * be maintained by the Tritonus team.\r\n\t * <p>\r\n\t * Every file reader, file writer, and format converter\r\n\t * provider should exclusively use this method for\r\n\t * retrieving instances of <code>AudioFormat.Encoding</code>.\r\n\t */\r\n\t/*\r\n\t MP2000/09/11:\r\n\t perhaps it is not a good idea to allow user programs the creation of new\r\n\t encodings. The problem with it is that a plain typo will produce an encoding\r\n\t object that is not supported. Instead, some indication of an error should be\r\n\t signaled to the user program. And, there should be a second interface for\r\n\t service providers allowing them to register encodings supported by themselves.\r\n\r\n\t $$fb2000/09/26:\r\n\t The problem is what you see as second issue: it can never be assured\r\n\t that this class knows all available encodings. So at the moment, there\r\n\t is no choice than to allow users to create any Encoding they wish.\r\n\t The encodings database will simplify things.\r\n\t A problem with an interface to retrieve supported encodings (or API\r\n\t function in spi.FormatConversionProvider) is that this requires\r\n\t loading of all providers very early. Hmmm, maybe this is necessary in any\r\n\t case when the user issues something like AudioSystem.isConversionSupported.\r\n\t */\r\n\tpublic static AudioFormat.Encoding getEncoding(String name) {\r\n\t\tAudioFormat.Encoding res=encodings.get(name);\r\n\t\tif (res==null) {\r\n\t\t\t// it is not already in the string set. Create a new encoding instance.\r\n\t\t\tres=new Encodings(name);\r\n\t\t\t// and save it for the future\r\n\t\t\tencodings.add(res);\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\t/**\r\n\t * Tests for equality of 2 encodings. They are equal when their strings match.\r\n\t * <p>\r\n\t * This function should be AudioFormat.Encoding.equals and must\r\n\t * be considered as a temporary work around until it flows into the\r\n\t * JavaSound API.\r\n\t */\r\n\t// IDEA: create a special \"NOT_SPECIFIED\" encoding\r\n\t// and a AudioFormat.Encoding.matches method.\r\n\tpublic static boolean equals(AudioFormat.Encoding e1, AudioFormat.Encoding e2) {\r\n\t\treturn e2.toString().equals(e1.toString());\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Returns all &quot;supported&quot; encodings.\r\n\t * Supported means that it is possible to read or\r\n\t * write files with this encoding, or that a converter\r\n\t * accepts this encoding as source or target format.\r\n\t * <p>\r\n\t * Currently, this method returns a best guess and\r\n\t * the search algorithm is far from complete: with standard\r\n\t * methods of AudioSystem, only the target encodings\r\n\t * of the converters can be retrieved - neither\r\n\t * the source encodings of converters nor the encodings\r\n\t * of file readers and file writers cannot be retrieved.\r\n\t */\r\n\tpublic static AudioFormat.Encoding[] getEncodings() {\r\n\t\tStringHashedSet<AudioFormat.Encoding> iteratedSources=new StringHashedSet<AudioFormat.Encoding>();\r\n\t\tStringHashedSet<AudioFormat.Encoding> retrievedTargets=new StringHashedSet<AudioFormat.Encoding>();\r\n\t\tIterator<AudioFormat.Encoding> sourceFormats=encodings.iterator();\r\n\t\twhile (sourceFormats.hasNext()) {\r\n\t\t\tAudioFormat.Encoding source=sourceFormats.next();\r\n\t\t\titerateEncodings(source, iteratedSources, retrievedTargets);\r\n\t\t}\r\n\t\treturn retrievedTargets.toArray(\r\n\t\t new AudioFormat.Encoding[retrievedTargets.size()]);\r\n\t}\r\n\r\n\r\n\tprivate static void iterateEncodings(AudioFormat.Encoding source,\r\n\t StringHashedSet<AudioFormat.Encoding> iteratedSources,\r\n\t StringHashedSet<AudioFormat.Encoding> retrievedTargets) {\r\n\t\tif (!iteratedSources.contains(source)) {\r\n\t\t\titeratedSources.add(source);\r\n\t\t\tAudioFormat.Encoding[] targets=AudioSystem.getTargetEncodings(source);\r\n\t\t\tfor (int i=0; i<targets.length; i++) {\r\n\t\t\t\tAudioFormat.Encoding target=targets[i];\r\n\t\t\t\tif (retrievedTargets.add(target)) {\r\n\t\t\t\t\titerateEncodings(target, iteratedSources,retrievedTargets);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r" }, { "identifier": "TEncodingFormatConversionProvider", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/convert/TEncodingFormatConversionProvider.java", "snippet": "public abstract class TEncodingFormatConversionProvider\r\nextends TSimpleFormatConversionProvider\r\n{\r\n\t\r\n\t/** create an instance. The given formats can be set to null. */\r\n\tprotected TEncodingFormatConversionProvider(\r\n\t Collection<AudioFormat> sourceFormats,\r\n\t Collection<AudioFormat> targetFormats)\r\n\t{\r\n\t\tsuper(sourceFormats, targetFormats);\r\n\t}\r\n\r\n\r\n\r\n\t/**\r\n\t * This implementation assumes that the converter can convert\r\n\t * from each of its source formats to each of its target\r\n\t * formats. If this is not the case, the converter has to\r\n\t * override this method.\r\n\t * <p>When conversion is supported, for every target encoding,\r\n\t * the fields sample size in bits, channels and sample rate are checked:\r\n\t * <ul>\r\n\t * <li>When a field in both the source and target format is AudioSystem.NOT_SPECIFIED,\r\n\t * one instance of that targetFormat is returned with this field set to AudioSystem.NOT_SPECIFIED.\r\n\t * <li>When a field in sourceFormat is set and it is AudioSystem.NOT_SPECIFIED in the target format,\r\n\t * the value of the field of source format is set in the returned format.\r\n\t * <li>The same applies for the other way round.\r\n\t * </ul>\r\n\t * For this, <code>replaceNotSpecified(sourceFormat, targetFormat)</code> in the base\r\n\t * class TSimpleFormatConversionProvider is used - and accordingly, the frameSize\r\n\t * is recalculated with <code>getFrameSize(...)</code> if a field with AudioSystem.NOT_SPECIFIED\r\n\t * is replaced. Inheriting classes may wish to override this method if the\r\n\t * default mode of calculating the frame size is not appropriate.\r\n\t */\r\n\t@Override\r\n\tpublic AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) {\r\n\t\tif (TDebug.TraceAudioConverter) {\r\n\t\t\tTDebug.out(\">TEncodingFormatConversionProvider.getTargetFormats(AudioFormat.Encoding, AudioFormat):\");\r\n\t\t\tTDebug.out(\"checking if conversion possible\");\r\n\t\t\tTDebug.out(\"from: \" + sourceFormat);\r\n\t\t\tTDebug.out(\"to: \" + targetEncoding);\r\n\t\t}\r\n\t\tif (isConversionSupported(targetEncoding, sourceFormat)) {\r\n\t\t\t// TODO: check that no duplicates may occur...\r\n\t\t\tArraySet<AudioFormat> result=new ArraySet<AudioFormat>();\r\n\t\t\tIterator<AudioFormat>\titerator = getCollectionTargetFormats().iterator();\r\n\t\t\twhile (iterator.hasNext()) {\r\n\t\t\t\tAudioFormat\ttargetFormat = iterator.next();\r\n\t\t\t\ttargetFormat=replaceNotSpecified(sourceFormat, targetFormat);\r\n\t\t\t\tresult.add(targetFormat);\r\n\t\t\t}\r\n\t\t\tif (TDebug.TraceAudioConverter) {\r\n\t\t\t\tTDebug.out(\"< returning \"+result.size()+\" elements.\");\r\n\t\t\t}\r\n\t\t\treturn result.toArray(EMPTY_FORMAT_ARRAY);\r\n\t\t} else {\r\n\t\t\tif (TDebug.TraceAudioConverter) {\r\n\t\t\t\tTDebug.out(\"< returning empty array.\");\r\n\t\t\t}\r\n\t\t\treturn EMPTY_FORMAT_ARRAY;\r\n\t\t}\r\n\t}\r\n\r\n}\r" } ]
import dev.mccue.mp3spi.mpeg.sampled.file.MpegEncoding; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.Encodings; import dev.mccue.tritonus.share.sampled.convert.TEncodingFormatConversionProvider; import java.util.Arrays; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem;
4,299
/* * MpegFormatConversionProvider. * * JavaZOOM : [email protected] * http://www.javazoom.net * * --------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -------------------------------------------------------------------------- */ package dev.mccue.mp3spi.mpeg.sampled.convert; /** * ConversionProvider for MPEG files. */ public class MpegFormatConversionProvider extends TEncodingFormatConversionProvider { private static final AudioFormat.Encoding MP3 = Encodings.getEncoding("MP3"); private static final AudioFormat.Encoding PCM_SIGNED = Encodings.getEncoding("PCM_SIGNED"); private static final AudioFormat[] INPUT_FORMATS = { // mono new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, false), new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, true), // stereo new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, false), new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, true), }; private static final AudioFormat[] OUTPUT_FORMATS = { // mono, 16 bit signed new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, false), new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, true), // stereo, 16 bit signed new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, false), new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, true), }; /** * Constructor. */ public MpegFormatConversionProvider() { super(Arrays.asList(INPUT_FORMATS), Arrays.asList(OUTPUT_FORMATS));
/* * MpegFormatConversionProvider. * * JavaZOOM : [email protected] * http://www.javazoom.net * * --------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -------------------------------------------------------------------------- */ package dev.mccue.mp3spi.mpeg.sampled.convert; /** * ConversionProvider for MPEG files. */ public class MpegFormatConversionProvider extends TEncodingFormatConversionProvider { private static final AudioFormat.Encoding MP3 = Encodings.getEncoding("MP3"); private static final AudioFormat.Encoding PCM_SIGNED = Encodings.getEncoding("PCM_SIGNED"); private static final AudioFormat[] INPUT_FORMATS = { // mono new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, false), new AudioFormat(MP3, -1.0F, -1, 1, -1, -1.0F, true), // stereo new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, false), new AudioFormat(MP3, -1.0F, -1, 2, -1, -1.0F, true), }; private static final AudioFormat[] OUTPUT_FORMATS = { // mono, 16 bit signed new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, false), new AudioFormat(PCM_SIGNED, -1.0F, 16, 1, 2, -1.0F, true), // stereo, 16 bit signed new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, false), new AudioFormat(PCM_SIGNED, -1.0F, 16, 2, 4, -1.0F, true), }; /** * Constructor. */ public MpegFormatConversionProvider() { super(Arrays.asList(INPUT_FORMATS), Arrays.asList(OUTPUT_FORMATS));
if (TDebug.TraceAudioConverter)
0
2023-10-19 14:09:37+00:00
8k
dvillavicencio/Riven-of-a-Thousand-Servers
src/test/java/com/danielvm/destiny2bot/integration/InteractionControllerTest.java
[ { "identifier": "BungieConfiguration", "path": "src/main/java/com/danielvm/destiny2bot/config/BungieConfiguration.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"bungie.api\")\npublic class BungieConfiguration implements OAuth2Configuration {\n\n /**\n * The name of the Bungie API key header\n */\n private static final String API_KEY_HEADER_NAME = \"x-api-key\";\n\n /**\n * API key provided by Bungie when registering an application in their portal\n */\n private String key;\n\n /**\n * Bungie clientId\n */\n private String clientId;\n\n /**\n * Bungie client secret\n */\n private String clientSecret;\n\n /**\n * Base url for Bungie Requests\n */\n private String baseUrl;\n\n /**\n * Url for Bungie Token endpoint\n */\n private String tokenUrl;\n\n /**\n * Url for OAuth2 authorization flow\n */\n private String authorizationUrl;\n\n /**\n * Url for callback during OAuth2 authorization\n */\n private String callbackUrl;\n\n @Bean\n public BungieClient bungieCharacterClient(WebClient.Builder builder) {\n var webClient = builder\n .baseUrl(this.baseUrl)\n .defaultHeader(API_KEY_HEADER_NAME, this.key)\n .build();\n return HttpServiceProxyFactory.builder()\n .exchangeAdapter(WebClientAdapter.create(webClient))\n .build()\n .createClient(BungieClient.class);\n }\n}" }, { "identifier": "DiscordConfiguration", "path": "src/main/java/com/danielvm/destiny2bot/config/DiscordConfiguration.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"discord.api\")\npublic class DiscordConfiguration implements OAuth2Configuration {\n\n /**\n * Base Url for Discord API calls\n */\n private String baseUrl;\n\n /**\n * The token for the Discord Bot\n */\n private String botToken;\n\n /**\n * The Bot's public key for verifying request signatures\n */\n private String botPublicKey;\n\n /**\n * The clientId for OAuth2 authentication\n */\n private String clientId;\n\n /**\n * The clientSecret for OAuth2 authentication\n */\n private String clientSecret;\n\n /**\n * The callback URL for OAuth2 authentication\n */\n private String callbackUrl;\n\n /**\n * The authorization url for OAuth2 authentication\n */\n private String authorizationUrl;\n\n /**\n * Token URL to retrieve access token for OAuth2\n */\n private String tokenUrl;\n\n /**\n * List of scopes for Discord OAuth2\n */\n private List<String> scopes;\n\n @Bean\n public DiscordClient discordClient(WebClient.Builder defaultBuilder) {\n var webClient = defaultBuilder\n .baseUrl(this.baseUrl)\n .build();\n return HttpServiceProxyFactory.builder()\n .exchangeAdapter(WebClientAdapter.create(webClient))\n .build()\n .createClient(DiscordClient.class);\n }\n}" }, { "identifier": "UserDetailsReactiveDao", "path": "src/main/java/com/danielvm/destiny2bot/dao/UserDetailsReactiveDao.java", "snippet": "@Repository\npublic class UserDetailsReactiveDao {\n\n private final ReactiveRedisTemplate<String, UserDetails> reactiveRedisTemplate;\n\n public UserDetailsReactiveDao(\n ReactiveRedisTemplate<String, UserDetails> reactiveRedisTemplate) {\n this.reactiveRedisTemplate = reactiveRedisTemplate;\n }\n\n /**\n * Save an entity to Redis if it was not previously present\n *\n * @param userDetails The entity to persist\n * @return True if it was successful, else returns False\n */\n public Mono<Boolean> save(UserDetails userDetails) {\n return reactiveRedisTemplate.opsForValue()\n .set(userDetails.getDiscordId(), userDetails);\n }\n\n /**\n * Return user details by their discordId\n *\n * @param discordId The discordId to find by\n * @return {@link UserDetails}\n */\n public Mono<UserDetails> getByDiscordId(String discordId) {\n return reactiveRedisTemplate.opsForValue().get(discordId);\n }\n\n /**\n * Returns if an entity with the given discordId exists\n *\n * @param discordId The discordId to check for\n * @return True if it exists, else False\n */\n public Mono<Boolean> existsByDiscordId(String discordId) {\n return reactiveRedisTemplate.opsForValue().get(discordId).hasElement();\n }\n}" }, { "identifier": "GenericResponse", "path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/GenericResponse.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GenericResponse<T> {\n\n /**\n * Most of the responses from Bungie.net have a Json element named 'Response' with arbitrary info\n * depending on the endpoint. This field is just a generic-wrapper for it.\n */\n @JsonAlias(\"Response\")\n @Nullable\n private T response;\n}" }, { "identifier": "MilestoneEntry", "path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/milestone/MilestoneEntry.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class MilestoneEntry {\n\n private String milestoneHash;\n private ZonedDateTime startDate;\n private ZonedDateTime endDate;\n private List<ActivitiesDto> activities;\n}" }, { "identifier": "DiscordUser", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/DiscordUser.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DiscordUser {\n\n /**\n * The user's Identification\n */\n private String id;\n\n /**\n * The user's username\n */\n private String username;\n}" }, { "identifier": "Interaction", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Interaction.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Interaction implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 315485352844067387L;\n\n /**\n * The Id of the interaction\n */\n private Object id;\n\n /**\n * The Id of the application\n */\n @JsonAlias(\"application_id\")\n private Object applicationId;\n\n /**\n * The type of the interaction (see {@link com.danielvm.destiny2bot.enums.InteractionType})\n */\n private Integer type;\n\n /**\n * Additional data of the interaction, will be attached to all interactions besides PING\n */\n private InteractionData data;\n\n /**\n * Member Data of the user that invoked the command\n */\n private Member member;\n\n}" }, { "identifier": "InteractionData", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/InteractionData.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class InteractionData {\n\n /**\n * The Id of the invoked command\n */\n private Object id;\n\n /**\n * The name of the invoked command\n */\n private String name;\n\n /**\n * The type of the invoked command\n */\n private Integer type;\n\n}" }, { "identifier": "Member", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Member.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Member {\n\n /**\n * Information about the user that sent the interaction\n */\n private DiscordUser user;\n}" }, { "identifier": "UserDetails", "path": "src/main/java/com/danielvm/destiny2bot/entity/UserDetails.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UserDetails implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 6161559188488304844L;\n\n private String discordId;\n\n private String discordUsername;\n\n private String accessToken;\n\n private String refreshToken;\n\n private Instant expiration;\n}" }, { "identifier": "InteractionType", "path": "src/main/java/com/danielvm/destiny2bot/enums/InteractionType.java", "snippet": "public enum InteractionType {\n PING(1),\n APPLICATION_COMMAND(2),\n MESSAGE_COMPONENT(3),\n APPLICATION_COMMAND_AUTOCOMPLETE(4),\n MODAL_SUBMIT(5);\n\n @Getter\n private final Integer type;\n\n InteractionType(Integer type) {\n this.type = type;\n }\n\n /**\n * Find an InteractionType type by their integer code\n *\n * @param type The integer code of the interaction\n * @return {@link InteractionType}\n */\n public static InteractionType findByValue(Integer type) {\n return Arrays.stream(InteractionType.values())\n .filter(it -> Objects.equals(it.type, type))\n .findFirst().orElse(null);\n }\n}" }, { "identifier": "ManifestEntity", "path": "src/main/java/com/danielvm/destiny2bot/enums/ManifestEntity.java", "snippet": "public enum ManifestEntity {\n\n BUCKET_DEFINITION(\"DestinyInventoryItemDefinition\"),\n STAT_DEFINITION(\"DestinyStatDefinition\"),\n CLASS_DEFINITION(\"DestinyClassDefinition\"),\n ITEM_INVENTORY_DEFINITION(\"DestinyInventoryItemDefinition\"),\n MILESTONE_DEFINITION(\"DestinyMilestoneDefinition\"),\n ACTIVITY_TYPE_DEFINITION(\"DestinyActivityTypeDefinition\"),\n ACTIVITY_DEFINITION(\"DestinyActivityDefinition\");\n\n @Getter\n private final String id;\n\n ManifestEntity(String id) {\n this.id = id;\n }\n}" }, { "identifier": "MessageUtil", "path": "src/main/java/com/danielvm/destiny2bot/util/MessageUtil.java", "snippet": "public class MessageUtil {\n\n private static final LocalTime DESTINY_2_STANDARD_RESET_TIME = LocalTime.of(9, 0);\n private static final ZoneId STANDARD_TIMEZONE = ZoneId.of(\"America/Los_Angeles\");\n public static final ZonedDateTime NEXT_TUESDAY = ZonedDateTime.of(\n LocalDate.now(STANDARD_TIMEZONE), DESTINY_2_STANDARD_RESET_TIME, STANDARD_TIMEZONE)\n .with(TemporalAdjusters.next(DayOfWeek.TUESDAY));\n public static final ZonedDateTime PREVIOUS_TUESDAY = ZonedDateTime.of(\n LocalDate.now(STANDARD_TIMEZONE), DESTINY_2_STANDARD_RESET_TIME, STANDARD_TIMEZONE)\n .with(TemporalAdjusters.previous(DayOfWeek.TUESDAY));\n\n /**\n * Formatter used to format the date for a message Example: the LocalDate object with date\n * 2023-01-01 would be formatted to \"Sunday 1st, January 2023\"\n */\n private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(\n \"EEEE d'%s', MMMM yyyy\");\n\n private MessageUtil() {\n }\n\n /**\n * Format the given local date using the class formatter, it also includes the correct suffix for\n * a date\n *\n * @param localDate the date to be formatted\n * @return String of the formatted local date\n */\n public static String formatDate(LocalDate localDate) {\n Integer dayOfMonth = localDate.getDayOfMonth();\n return FORMATTER.format(localDate)\n .formatted(suffix(dayOfMonth));\n }\n\n private static String suffix(Integer dayOfMonth) {\n if (dayOfMonth >= 11 && dayOfMonth <= 13) {\n return \"th\";\n }\n return switch (dayOfMonth % 10) {\n case 1 -> \"st\";\n case 2 -> \"nd\";\n case 3 -> \"rd\";\n default -> \"th\";\n };\n }\n\n}" }, { "identifier": "OAuth2Util", "path": "src/main/java/com/danielvm/destiny2bot/util/OAuth2Util.java", "snippet": "@Validated\npublic class OAuth2Util {\n\n private static final String BEARER_TOKEN_FORMAT = \"Bearer %s\";\n\n private OAuth2Util() {\n }\n\n /**\n * Format the given token to bearer token format\n *\n * @param token The token to format\n * @return The formatted String\n */\n public static String formatBearerToken(String token) {\n return BEARER_TOKEN_FORMAT.formatted(token);\n }\n\n /**\n * Build body parameters for a token request to an OAuth2 resource provider\n *\n * @param authorizationCode The authorization code\n * @param redirectUri The redirect type\n * @param clientSecret The client secret\n * @param clientId The clientId\n * @return {@link MultiValueMap} of OAuth2 attributes for Token exchange\n */\n public static MultiValueMap<String, String> buildTokenExchangeParameters(\n String authorizationCode,\n String redirectUri,\n String clientSecret,\n String clientId) {\n MultiValueMap<String, String> map = new LinkedMultiValueMap<>();\n map.add(OAuth2Params.CODE, authorizationCode);\n map.add(OAuth2Params.GRANT_TYPE, OAuth2Params.AUTHORIZATION_CODE);\n map.add(OAuth2Params.REDIRECT_URI, redirectUri);\n map.add(OAuth2Params.CLIENT_SECRET, clientSecret);\n map.add(OAuth2Params.CLIENT_ID, clientId);\n return map;\n }\n\n /**\n * Build body parameters for a token request to an OAuth2 resource provider\n *\n * @param refreshToken The refresh token to send\n * @return {@link MultiValueMap} of OAuth2 attributes for refresh token exchange\n */\n public static MultiValueMap<String, String> buildRefreshTokenExchangeParameters(\n String refreshToken, String clientId, String clientSecret) {\n MultiValueMap<String, String> map = new LinkedMultiValueMap<>();\n map.add(OAuth2Params.GRANT_TYPE, OAuth2Params.REFRESH_TOKEN);\n map.add(OAuth2Params.REFRESH_TOKEN, refreshToken);\n map.add(OAuth2Params.CLIENT_ID, clientId);\n map.add(OAuth2Params.CLIENT_SECRET, clientSecret);\n return map;\n }\n\n /**\n * Return the qualified url with all parameters\n *\n * @param bungieConfiguration The config class containing all necessary information to build the\n * authorization URI\n * @return The authorization url with all required parameters\n */\n public static String bungieAuthorizationUrl(String authUrl, String clientId) {\n return UriComponentsBuilder\n .fromHttpUrl(authUrl)\n .queryParam(OAuth2Params.RESPONSE_TYPE, OAuth2Params.CODE)\n .queryParam(OAuth2Params.CLIENT_ID, clientId)\n .build().toString();\n }\n\n /**\n * Returns a registration link based on some OAuth2 parameters. This URL can be used to register\n * the bot to an end-user's Discord server\n *\n * @param authUrl The authorization URL parameter\n * @param clientId The clientId parameter\n * @param callbackUrl The callback URL parameter\n * @param scopes The scopes parameter\n * @return a String with the above parameters\n */\n public static String discordAuthorizationUrl(\n String authUrl, String clientId, String callbackUrl, String scopes) {\n return UriComponentsBuilder.fromHttpUrl(authUrl)\n .queryParam(OAuth2Params.CLIENT_ID, clientId)\n .queryParam(OAuth2Params.REDIRECT_URI,\n URLEncoder.encode(callbackUrl, StandardCharsets.UTF_8))\n .queryParam(OAuth2Params.RESPONSE_TYPE, OAuth2Params.CODE)\n .queryParam(OAuth2Params.SCOPE, scopes).build().toString();\n }\n\n}" } ]
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.assertj.core.api.Assertions.assertThat; import com.danielvm.destiny2bot.config.BungieConfiguration; import com.danielvm.destiny2bot.config.DiscordConfiguration; import com.danielvm.destiny2bot.dao.UserDetailsReactiveDao; import com.danielvm.destiny2bot.dto.destiny.GenericResponse; import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry; import com.danielvm.destiny2bot.dto.discord.DiscordUser; import com.danielvm.destiny2bot.dto.discord.Interaction; import com.danielvm.destiny2bot.dto.discord.InteractionData; import com.danielvm.destiny2bot.dto.discord.Member; import com.danielvm.destiny2bot.entity.UserDetails; import com.danielvm.destiny2bot.enums.InteractionType; import com.danielvm.destiny2bot.enums.ManifestEntity; import com.danielvm.destiny2bot.util.MessageUtil; import com.danielvm.destiny2bot.util.OAuth2Util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.PublicKey; import java.time.Instant; import java.util.Map; import java.util.Objects; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import org.springframework.web.reactive.function.BodyInserters; import software.pando.crypto.nacl.Crypto;
4,738
package com.danielvm.destiny2bot.integration; public class InteractionControllerTest extends BaseIntegrationTest { private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF"; private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC"; // Static mapper to be used on the @BeforeAll static method private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper()) .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build() .registerModule(new JavaTimeModule()); @Autowired BungieConfiguration bungieConfiguration; @Autowired DiscordConfiguration discordConfiguration; @Autowired UserDetailsReactiveDao userDetailsReactiveDao; /** * This method replaces all the placeholder values in the milestones-response.json file The reason * for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are * not dynamic, therefore this method * * @throws IOException in case we are not able to write back to the file (in-place) */ @BeforeAll public static void before() throws IOException { File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json"); TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() { }; var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference); replaceDates(milestoneResponse, "526718853"); replaceDates(milestoneResponse, "2712317338"); OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse); } private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response, String hash) { response.getResponse().entrySet().stream() .filter(entry -> Objects.equals(entry.getKey(), hash)) .forEach(entry -> { var startDate = entry.getValue().getStartDate(); var endDate = entry.getValue().getEndDate(); if (Objects.nonNull(startDate)) { entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY); } if (Objects.nonNull(endDate)) { entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY); } }); }
package com.danielvm.destiny2bot.integration; public class InteractionControllerTest extends BaseIntegrationTest { private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF"; private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC"; // Static mapper to be used on the @BeforeAll static method private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper()) .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build() .registerModule(new JavaTimeModule()); @Autowired BungieConfiguration bungieConfiguration; @Autowired DiscordConfiguration discordConfiguration; @Autowired UserDetailsReactiveDao userDetailsReactiveDao; /** * This method replaces all the placeholder values in the milestones-response.json file The reason * for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are * not dynamic, therefore this method * * @throws IOException in case we are not able to write back to the file (in-place) */ @BeforeAll public static void before() throws IOException { File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json"); TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() { }; var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference); replaceDates(milestoneResponse, "526718853"); replaceDates(milestoneResponse, "2712317338"); OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse); } private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response, String hash) { response.getResponse().entrySet().stream() .filter(entry -> Objects.equals(entry.getKey(), hash)) .forEach(entry -> { var startDate = entry.getValue().getStartDate(); var endDate = entry.getValue().getEndDate(); if (Objects.nonNull(startDate)) { entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY); } if (Objects.nonNull(endDate)) { entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY); } }); }
private String createValidSignature(Interaction body, String timestamp)
6
2023-10-20 05:53:03+00:00
8k
MinecraftForge/ModLauncher
ml-test/src/test/java/net/minecraftforge/modlauncher/test/TransformationServiceDecoratorTests.java
[ { "identifier": "TransformList", "path": "src/main/java/cpw/mods/modlauncher/TransformList.java", "snippet": "@SuppressWarnings(\"WeakerAccess\")\npublic class TransformList<T> {\n private final Map<TransformTargetLabel, List<ITransformer<T>>> transformers = new ConcurrentHashMap<>();\n private final Class<T> nodeType;\n\n TransformList(Class<T> nodeType) {\n this.nodeType = nodeType;\n }\n\n /**\n * Testing only\n * @return a map\n */\n private Map<TransformTargetLabel, List<ITransformer<T>>> getTransformers() {\n return transformers;\n }\n\n void addTransformer(TransformTargetLabel targetLabel, ITransformer<T> transformer) {\n // thread safety - compute if absent to insert the list\n transformers.computeIfAbsent(targetLabel, v -> new ArrayList<>());\n // thread safety - compute if present to mutate the list under the protection of the CHM\n transformers.computeIfPresent(targetLabel, (k,l)-> { l.add(transformer); return l;});\n }\n\n List<ITransformer<T>> getTransformersForLabel(TransformTargetLabel label) {\n // thread safety - compute if absent to insert the list\n return transformers.computeIfAbsent(label, v-> new ArrayList<>());\n }\n}" }, { "identifier": "TransformStore", "path": "src/main/java/cpw/mods/modlauncher/TransformStore.java", "snippet": "public class TransformStore {\n private static final Logger LOGGER = LogManager.getLogger();\n private final Set<String> classNeedsTransforming = new HashSet<>();\n private final EnumMap<TransformTargetLabel.LabelType, TransformList<?>> transformers;\n\n public TransformStore() {\n transformers = new EnumMap<>(TransformTargetLabel.LabelType.class);\n for (TransformTargetLabel.LabelType type : TransformTargetLabel.LabelType.values())\n transformers.put(type, new TransformList<>(type.getNodeType()));\n }\n\n List<ITransformer<FieldNode>> getTransformersFor(String className, FieldNode field) {\n TransformTargetLabel tl = new TransformTargetLabel(className, field.name);\n TransformList<FieldNode> transformerlist = TransformTargetLabel.LabelType.FIELD.getFromMap(this.transformers);\n return transformerlist.getTransformersForLabel(tl);\n }\n\n List<ITransformer<MethodNode>> getTransformersFor(String className, MethodNode method) {\n TransformTargetLabel tl = new TransformTargetLabel(className, method.name, method.desc);\n TransformList<MethodNode> transformerlist = TransformTargetLabel.LabelType.METHOD.getFromMap(this.transformers);\n return transformerlist.getTransformersForLabel(tl);\n }\n\n List<ITransformer<ClassNode>> getTransformersFor(String className, TransformTargetLabel.LabelType classType) {\n TransformTargetLabel tl = new TransformTargetLabel(className, classType);\n TransformList<ClassNode> transformerlist = classType.getFromMap(this.transformers);\n return transformerlist.getTransformersForLabel(tl);\n }\n\n @SuppressWarnings(\"unchecked\")\n <T> void addTransformer(TransformTargetLabel targetLabel, ITransformer<T> transformer, ITransformationService service) {\n LOGGER.debug(MODLAUNCHER,\"Adding transformer {} to {}\", () -> transformer, () -> targetLabel);\n classNeedsTransforming.add(targetLabel.getClassName().getInternalName());\n final TransformList<T> transformList = (TransformList<T>) this.transformers.get(targetLabel.getLabelType());\n transformList.addTransformer(targetLabel, new TransformerHolder<>(transformer, service));\n }\n\n /**\n * Requires internal class name (using '/' instead of '.')\n */\n boolean needsTransforming(String internalClassName) {\n return classNeedsTransforming.contains(internalClassName);\n }\n}" }, { "identifier": "TransformTargetLabel", "path": "src/main/java/cpw/mods/modlauncher/TransformTargetLabel.java", "snippet": "public final class TransformTargetLabel {\n\n private final Type className;\n private final String elementName;\n private final Type elementDescriptor;\n private final LabelType labelType;\n TransformTargetLabel(ITransformer.Target target) {\n this(target.getClassName(), target.getElementName(), target.getElementDescriptor(), LabelType.valueOf(target.getTargetType().name()));\n }\n private TransformTargetLabel(String className, String elementName, String elementDescriptor, LabelType labelType) {\n this.className = Type.getObjectType(className.replace('.', '/'));\n this.elementName = elementName;\n this.elementDescriptor = elementDescriptor.length() > 0 ? Type.getMethodType(elementDescriptor) : Type.VOID_TYPE;\n this.labelType = labelType;\n }\n public TransformTargetLabel(String className, String fieldName) {\n this(className, fieldName, \"\", FIELD);\n }\n\n TransformTargetLabel(String className, String methodName, String methodDesc) {\n this(className, methodName, methodDesc, METHOD);\n }\n\n @Deprecated\n public TransformTargetLabel(String className) {\n this(className, \"\", \"\", CLASS);\n }\n\n public TransformTargetLabel(String className, LabelType type) {\n this(className, \"\", \"\", type);\n if (type.nodeType != ClassNode.class)\n throw new IllegalArgumentException(\"Invalid type \" + type + \", must be for class!\");\n }\n\n final Type getClassName() {\n return this.className;\n }\n\n public final String getElementName() {\n return this.elementName;\n }\n\n public final Type getElementDescriptor() {\n return this.elementDescriptor;\n }\n\n final LabelType getLabelType() {\n return this.labelType;\n }\n\n public int hashCode() {\n return Objects.hash(this.className, this.elementName, this.elementDescriptor);\n }\n\n @Override\n public boolean equals(Object obj) {\n try {\n TransformTargetLabel tl = (TransformTargetLabel) obj;\n return Objects.equals(this.className, tl.className)\n && Objects.equals(this.elementName, tl.elementName)\n && Objects.equals(this.elementDescriptor, tl.elementDescriptor);\n } catch (ClassCastException cce) {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return \"Target : \" + Objects.toString(labelType) + \" {\" + Objects.toString(className) + \"} {\" + Objects.toString(elementName) + \"} {\" + Objects.toString(elementDescriptor) + \"}\";\n }\n\n public enum LabelType {\n FIELD(FieldNode.class),\n METHOD(MethodNode.class),\n CLASS(ClassNode.class),\n PRE_CLASS(ClassNode.class);\n\n private final Class<?> nodeType;\n\n LabelType(Class<?> nodeType) {\n this.nodeType = nodeType;\n }\n\n public Class<?> getNodeType() {\n return nodeType;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <V> TransformList<V> getFromMap(EnumMap<LabelType, TransformList<?>> transformers) {\n return get(transformers, (Class<V>) this.nodeType);\n }\n\n @SuppressWarnings(\"unchecked\")\n private <V> TransformList<V> get(EnumMap<LabelType, TransformList<?>> transformers, Class<V> type) {\n return (TransformList<V>) transformers.get(this);\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> Supplier<TransformList<T>> mapSupplier(EnumMap<LabelType, TransformList<?>> transformers) {\n return () -> (TransformList<T>) transformers.get(this);\n }\n\n }\n}" }, { "identifier": "TransformationServiceDecorator", "path": "src/main/java/cpw/mods/modlauncher/TransformationServiceDecorator.java", "snippet": "public class TransformationServiceDecorator {\n private static final Logger LOGGER = LogManager.getLogger();\n private final ITransformationService service;\n private boolean isValid;\n\n TransformationServiceDecorator(ITransformationService service) {\n this.service = service;\n }\n\n void onLoad(IEnvironment env, Set<String> otherServices) {\n try {\n LOGGER.debug(MODLAUNCHER,\"Loading service {}\", this.service::name);\n this.service.onLoad(env, otherServices);\n this.isValid = true;\n LOGGER.debug(MODLAUNCHER,\"Loaded service {}\", this.service::name);\n } catch (IncompatibleEnvironmentException e) {\n LOGGER.error(MODLAUNCHER,\"Service failed to load {}\", this.service.name(), e);\n this.isValid = false;\n }\n }\n\n boolean isValid() {\n return isValid;\n }\n\n void onInitialize(IEnvironment environment) {\n LOGGER.debug(MODLAUNCHER,\"Initializing transformation service {}\", this.service::name);\n this.service.initialize(environment);\n LOGGER.debug(MODLAUNCHER,\"Initialized transformation service {}\", this.service::name);\n }\n\n public void gatherTransformers(TransformStore transformStore) {\n LOGGER.debug(MODLAUNCHER, \"Initializing transformers for transformation service {}\", this.service::name);\n var transformers = this.service.transformers();\n Objects.requireNonNull(transformers, \"The transformers list should not be null\");\n\n for (ITransformer<?> transformer : transformers) {\n Type type = null;\n var genericInterfaces = transformer.getClass().getGenericInterfaces();\n for (var typ : genericInterfaces) {\n if (typ instanceof ParameterizedType pt && pt.getRawType().equals(ITransformer.class)) {\n type = pt.getActualTypeArguments()[0];\n break;\n }\n }\n\n if (type == null) {\n LOGGER.error(MODLAUNCHER, \"Invalid Transformer, could not determine generic type {}\", transformer.getClass().getSimpleName());\n throw new IllegalArgumentException(\"Invalid Transformer, could not determine generic type \" + transformer.getClass().getSimpleName());\n }\n\n LabelType seen = null;\n for (var target : transformer.targets()) {\n var label = new TransformTargetLabel(target);\n if (\n (seen != null && label.getLabelType() != seen) ||\n !label.getLabelType().getNodeType().getName().equals(type.getTypeName())\n ) {\n LOGGER.info(MODLAUNCHER, \"Invalid target {} for transformer {}\", label.getLabelType(), transformer);\n throw new IllegalArgumentException(\"Invalid target \" + label.getLabelType() + \" for transformer \" + transformer);\n }\n\n seen = label.getLabelType();\n transformStore.addTransformer(label, transformer, service);\n }\n }\n LOGGER.debug(MODLAUNCHER, \"Initialized transformers for transformation service {}\", this.service::name);\n }\n\n ITransformationService getService() {\n return service;\n }\n\n List<ITransformationService.Resource> runScan(final Environment environment) {\n LOGGER.debug(MODLAUNCHER,\"Beginning scan trigger - transformation service {}\", this.service::name);\n final List<ITransformationService.Resource> scanResults = this.service.beginScanning(environment);\n LOGGER.debug(MODLAUNCHER,\"End scan trigger - transformation service {}\", this.service::name);\n return scanResults;\n }\n\n public List<ITransformationService.Resource> onCompleteScan(IModuleLayerManager moduleLayerManager) {\n return this.service.completeScan(moduleLayerManager);\n }\n}" }, { "identifier": "ITransformer", "path": "src/main/java/cpw/mods/modlauncher/api/ITransformer.java", "snippet": "public interface ITransformer<T> {\n\n String[] DEFAULT_LABEL = {\"default\"};\n\n /**\n * Transform the input to the ITransformer's desire. The context from the last vote is\n * provided as well.\n *\n * @param input The ASM input node, which can be mutated directly\n * @param context The voting context\n * @return An ASM node of the same type as that supplied. It will be used for subsequent\n * rounds of voting.\n */\n @NotNull\n T transform(T input, ITransformerVotingContext context);\n\n /**\n * Return the {@link TransformerVoteResult} for this transformer.\n * The transformer should evaluate whether or not is is a candidate to apply during\n * the round of voting in progress, represented by the context parameter.\n * How the vote works:\n * <ul>\n * <li>If the transformer wishes to be a candidate, it should return {@link TransformerVoteResult#YES}.</li>\n * <li>If the transformer wishes to exit the voting (the transformer has already\n * has its intended change applied, for example), it should return {@link TransformerVoteResult#NO}</li>\n * <li>If the transformer wishes to wait for future rounds of voting it should return\n * {@link TransformerVoteResult#DEFER}. Note that if there is <em>no</em> YES candidate, but DEFER\n * candidates remain, this is a DEFERRAL stalemate and the game will crash.</li>\n * <li>If the transformer wishes to crash the game, it should return {@link TransformerVoteResult#REJECT}.\n * This is extremely frowned upon, and should not be used except in extreme circumstances. If an\n * incompatibility is present, it should detect and handle it in the {@link ITransformationService#onLoad}\n * </li>\n * </ul>\n * After all votes from candidate transformers are collected, the NOs are removed from the\n * current set of voters, one from the set of YES voters is selected and it's {@link ITransformer#transform(Object, ITransformerVotingContext)}\n * method called. It is then removed from the set of transformers and another round is performed.\n *\n * @param context The context of the vote\n * @return A TransformerVoteResult indicating the desire of this transformer\n */\n @NotNull\n TransformerVoteResult castVote(ITransformerVotingContext context);\n\n /**\n * Return a set of {@link Target} identifying which elements this transformer wishes to try\n * and apply to. The {@link Target#getTargetType()} must match the T variable for the transformer\n * as documented in {@link TargetType}, other combinations will be rejected.\n *\n * @return The set of targets this transformer wishes to apply to\n */\n @NotNull\n Set<Target> targets();\n\n /**\n * @return A string array for uniquely identifying this transformer instance within the service.\n */\n default String[] labels() {\n return DEFAULT_LABEL;\n }\n /**\n * Specifies the target type for the {@link Target}. Note that the type of the transformer T\n * dictates what are acceptable targets for this transformer.\n */\n enum TargetType {\n /**\n * Target a class. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.ClassNode}\n */\n CLASS,\n /**\n * Target a method. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.MethodNode}\n */\n METHOD,\n /**\n * Target a field. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.FieldNode}\n */\n FIELD,\n /**\n * Target a class, before field and method transforms operate. SHOULD ONLY BE USED to \"replace\" a complete class\n * The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.ClassNode}\n */\n PRE_CLASS;\n }\n\n /**\n * Simple data holder indicating where the {@link ITransformer} can target.\n */\n @SuppressWarnings(\"SameParameterValue\")\n final class Target {\n private final String className;\n private final String elementName;\n private final String elementDescriptor;\n private final TargetType targetType;\n\n /**\n * Build a new target. Ensure that the targetType matches the T type for the ITransformer\n * supplying the target.\n * <p>\n * In an obfuscated environment, this will be the obfuscated \"notch\" naming, in a\n * deobfuscated environment this will be the searge naming.\n *\n * @param className The name of the class being targetted\n * @param elementName The name of the element being targetted. This is the field name for a field,\n * the method name for a method. Empty string for other types\n * @param elementDescriptor The method's descriptor. Empty string for other types\n * @param targetType The {@link TargetType} for this target - it should match the ITransformer\n * type variable T\n */\n Target(String className, String elementName, String elementDescriptor, TargetType targetType) {\n Objects.requireNonNull(className, \"Class Name cannot be null\");\n Objects.requireNonNull(elementName, \"Element Name cannot be null\");\n Objects.requireNonNull(elementDescriptor, \"Element Descriptor cannot be null\");\n Objects.requireNonNull(targetType, \"Target Type cannot be null\");\n this.className = className;\n this.elementName = elementName;\n this.elementDescriptor = elementDescriptor;\n this.targetType = targetType;\n }\n\n /**\n * Convenience method returning a {@link Target} for a class\n *\n * @param className The name of the class\n * @return A target for the named class\n */\n @NotNull\n public static Target targetClass(String className) {\n return new Target(className, \"\", \"\", TargetType.CLASS);\n }\n\n /**\n * Convenience method returning a {@link Target} for a class (prior to other loading operations)\n *\n * @param className The name of the class\n * @return A target for the named class\n */\n @NotNull\n public static Target targetPreClass(String className) {\n return new Target(className, \"\", \"\", TargetType.PRE_CLASS);\n }\n /**\n * Convenience method return a {@link Target} for a method\n *\n * @param className The name of the class containing the method\n * @param methodName The name of the method\n * @param methodDescriptor The method's descriptor string\n * @return A target for the named method\n */\n @NotNull\n public static Target targetMethod(String className, String methodName, String methodDescriptor) {\n return new Target(className, methodName, methodDescriptor, TargetType.METHOD);\n }\n\n /**\n * Convenience method returning a {@link Target} for a field\n *\n * @param className The name of the class containing the field\n * @param fieldName The name of the field\n * @return A target for the named field\n */\n @NotNull\n public static Target targetField(String className, String fieldName) {\n return new Target(className, fieldName, \"\", TargetType.FIELD);\n }\n\n /**\n * @return The class name for this target\n */\n public String getClassName() {\n return className;\n }\n\n /**\n * @return The element name for this target, either the field name or the method name\n */\n public String getElementName() {\n return elementName;\n }\n\n /**\n * @return The element's descriptor. Usually the method descriptor\n */\n public String getElementDescriptor() {\n return elementDescriptor;\n }\n\n /**\n * @return The target type of this target\n */\n public TargetType getTargetType() {\n return targetType;\n }\n }\n}" }, { "identifier": "ITransformerVotingContext", "path": "src/main/java/cpw/mods/modlauncher/api/ITransformerVotingContext.java", "snippet": "public interface ITransformerVotingContext {\n /**\n * @return The class name being transformed\n */\n String getClassName();\n\n /**\n * @return If the class already existed\n */\n boolean doesClassExist();\n\n /**\n * @return The initial sha256 checksum of the class bytes.\n */\n byte[] getInitialClassSha256();\n\n /**\n * @return The activities already performed on this class. This list is read only, but will change as activities happen.\n */\n List<ITransformerActivity> getAuditActivities();\n\n String getReason();\n\n /**\n * Return the result of applying the supplied field predicate to the current field node.\n * Can only be used on a Field target.\n *\n * @param fieldPredicate The field predicate\n * @return true if the predicate passed\n */\n boolean applyFieldPredicate(FieldPredicate fieldPredicate);\n\n /**\n * Return the result of applying the supplied method predicate to the current method node.\n * Can only be used on a Method target.\n *\n * @param methodPredicate The method predicate\n * @return true if the predicate passed\n */\n boolean applyMethodPredicate(MethodPredicate methodPredicate);\n\n /**\n * Return the result of applying the supplied class predicate to the current class node.\n * Can only be used on a Class target.\n *\n * @param classPredicate The class predicate\n * @return true if the predicate passed\n */\n boolean applyClassPredicate(ClassPredicate classPredicate);\n\n /**\n * Return the result of applying the supplied instruction predicate to the current method node.\n * Can only be used on a Method target.\n *\n * @param insnPredicate The insn predicate\n * @return true if the predicate passed\n */\n boolean applyInstructionPredicate(InsnPredicate insnPredicate);\n\n interface FieldPredicate {\n boolean test(final int access, final String name, final String descriptor, final String signature, final Object value);\n }\n\n interface MethodPredicate {\n boolean test(final int access, final String name, final String descriptor, final String signature, final String[] exceptions);\n }\n\n interface ClassPredicate {\n boolean test(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces);\n }\n\n interface InsnPredicate {\n boolean test(final int insnCount, final int opcode, Object... args);\n }\n}" }, { "identifier": "TransformerVoteResult", "path": "src/main/java/cpw/mods/modlauncher/api/TransformerVoteResult.java", "snippet": "public enum TransformerVoteResult {\n YES, DEFER, NO, REJECT\n}" } ]
import cpw.mods.modlauncher.TransformList; import cpw.mods.modlauncher.TransformStore; import cpw.mods.modlauncher.TransformTargetLabel; import cpw.mods.modlauncher.TransformationServiceDecorator; import cpw.mods.modlauncher.api.ITransformer; import cpw.mods.modlauncher.api.ITransformerVotingContext; import cpw.mods.modlauncher.api.TransformerVoteResult; import net.minecraftforge.unsafe.UnsafeHacks; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue;
5,341
/* * Copyright (c) Forge Development LLC * SPDX-License-Identifier: LGPL-3.0-only */ package net.minecraftforge.modlauncher.test; class TransformationServiceDecoratorTests { private final ClassNodeTransformer classNodeTransformer = new ClassNodeTransformer(); private final MethodNodeTransformer methodNodeTransformer = new MethodNodeTransformer(); @Test void testGatherTransformersNormally() throws Exception { UnsafeHacksUtil.hackPowermock(); MockTransformerService mockTransformerService = new MockTransformerService() { @NotNull @Override public List<ITransformer> transformers() { return Stream.of(classNodeTransformer, methodNodeTransformer).collect(Collectors.toList()); } };
/* * Copyright (c) Forge Development LLC * SPDX-License-Identifier: LGPL-3.0-only */ package net.minecraftforge.modlauncher.test; class TransformationServiceDecoratorTests { private final ClassNodeTransformer classNodeTransformer = new ClassNodeTransformer(); private final MethodNodeTransformer methodNodeTransformer = new MethodNodeTransformer(); @Test void testGatherTransformersNormally() throws Exception { UnsafeHacksUtil.hackPowermock(); MockTransformerService mockTransformerService = new MockTransformerService() { @NotNull @Override public List<ITransformer> transformers() { return Stream.of(classNodeTransformer, methodNodeTransformer).collect(Collectors.toList()); } };
TransformStore store = new TransformStore();
1
2023-10-18 17:56:01+00:00
8k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/modules/combat/AutoBlock.java
[ { "identifier": "KyroClient", "path": "Client/src/main/java/me/kyroclient/KyroClient.java", "snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public static ModuleManager moduleManager;\n public static NotificationManager notificationManager;\n public static ConfigManager configManager;\n public static ThemeManager themeManager;\n public static FriendManager friendManager;\n public static CapeManager capeManager;\n public static Minecraft mc;\n public static boolean isDev = true;\n public static Color iconColor = new Color(237, 107, 0);\n public static long gameStarted;\n public static boolean banned = false;\n\n //Module Dependencies\n public static Gui clickGui;\n public static NickHider nickHider;\n public static CropNuker cropNuker;\n public static Velocity velocity;\n public static FastPlace fastPlace;\n public static Modless modless;\n public static Speed speed;\n public static AntiBot antiBot;\n public static Interfaces interfaces;\n public static Delays delays;\n public static Hitboxes hitBoxes;\n public static NoSlow noSlow;\n public static FreeCam freeCam;\n public static Giants giants;\n public static Animations animations;\n public static Aura aura;\n public static AutoBlock autoBlock;\n public static PopupAnimation popupAnimation;\n public static GuiMove guiMove;\n public static Camera camera;\n public static Reach reach;\n public static InventoryDisplay inventoryDisplay;\n public static LoreDisplay loreDisplay;\n public static FarmingMacro macro;\n public static MiningQOL miningQol;\n public static Tickless tickless;\n public static TeleportExploit teleportExploit;\n public static Hud hud;\n public static FakeLag fakeLag;\n public static Proxy proxy;\n public static CustomBrand customBrand;\n public static NoFallingBlocks noFallingBlocks;\n public static PlayerVisibility playerVisibility;\n public static NoDebuff noDebuff;\n public static Capes capes;\n\n\n //Methods\n\n /*\n Time to finally make it spoof being any random mod on boot!\n */\n public static List<ForgeRegister> registerEvents()\n {\n /*for (Module module : moduleManager.getModules())\n {\n MinecraftForge.EVENT_BUS.register(module);\n }*/\n\n ForgeSpoofer.update();\n List<ForgeRegister> registers = new ArrayList<>();\n\n for (Module module : moduleManager.getModules())\n {\n List<ForgeRegister> register = ForgeSpoofer.register(module, true);\n if (register.isEmpty()) continue;\n registers.addAll(register);\n }\n\n registers.add(ForgeSpoofer.register(notificationManager = new NotificationManager(), true).get(0));\n registers.add(ForgeSpoofer.register(new BlurUtils(), true).get(0));\n registers.add(ForgeSpoofer.register(new KyroClient(), true).get(0));\n\n Fonts.bootstrap();\n\n capeManager = new CapeManager();\n try {\n capeManager.init();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return registers;\n }\n public static void init()\n {\n mc = Minecraft.getMinecraft();\n\n moduleManager = new ModuleManager(\"me.kyroclient.modules\");\n moduleManager.initReflection();\n\n configManager = new ConfigManager();\n themeManager = new ThemeManager();\n friendManager = new FriendManager();\n\n friendManager.init();\n\n CommandManager.init();\n\n KyroClient.proxy.setToggled(false);\n\n gameStarted = System.currentTimeMillis();\n\n //fixCertificate();\n\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n friendManager.save();\n try {\n Class clazz = Class.forName(\"me.kyroclient.AgentLoader\");\n Method method = clazz.getMethod(\"downloadUpdate\");\n method.setAccessible(true);\n method.invoke(null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }));\n\n new Thread(KyroClient::threadTask).start();\n }\n\n @SneakyThrows\n public static void fixCertificate()\n {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());\n HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());\n HostnameVerifier allHostsValid = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);\n }\n\n @SubscribeEvent\n public void sendPacket(PacketSentEvent event)\n {\n if (event.packet instanceof C01PacketChatMessage)\n {\n C01PacketChatMessage message = (C01PacketChatMessage) event.packet;\n\n String str = message.getMessage();\n\n if (CommandManager.handle(str))\n {\n event.setCanceled(true);\n }\n }\n }\n\n public static void sendMessage(String message)\n {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n @SneakyThrows\n public static void threadTask()\n {\n URL url2 = new URL(\"https://raw.githubusercontent.com/Kyrotechnic/KyroClient/main/update/Changelog.txt\");\n\n List<String> changelog = new ArrayList<String>();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(url2.openStream()));\n String b = null;\n while ((b = reader.readLine()) != null)\n {\n changelog.add(b);\n }\n\n KyroClient.VERSION = changelog.get(0);\n\n KyroClient.changelog = changelog.stream().filter(c -> !(c.equals(KyroClient.VERSION))).collect(Collectors.toList());\n }\n\n public static void handleKey(int key)\n {\n for (Module module : moduleManager.getModules())\n {\n if (module.getKeycode() == key)\n {\n module.toggle();\n if (!clickGui.disableNotifs.isEnabled())\n notificationManager.showNotification(module.getName() + \" has been \" + (module.isToggled() ? \"Enabled\" : \"Disabled\"), 2000, Notification.NotificationType.INFO);\n }\n }\n }\n\n public static int ticks = 0;\n\n @SubscribeEvent\n public void joinWorld(TickEvent.ClientTickEvent event)\n {\n ticks++;\n SkyblockUtils.tick(event);\n }\n}" }, { "identifier": "MotionUpdateEvent", "path": "Client/src/main/java/me/kyroclient/events/MotionUpdateEvent.java", "snippet": "@Cancelable\npublic class MotionUpdateEvent extends Event\n{\n public float yaw;\n public float pitch;\n public double x;\n public double y;\n public double z;\n public boolean onGround;\n public boolean sprinting;\n public boolean sneaking;\n\n protected MotionUpdateEvent(final double x, final double y, final double z, final float yaw, final float pitch, final boolean onGround, final boolean sprinting, final boolean sneaking) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.yaw = yaw;\n this.pitch = pitch;\n this.onGround = onGround;\n this.sneaking = sneaking;\n this.sprinting = sprinting;\n }\n\n public MotionUpdateEvent setPosition(final double x, final double y, final double z) {\n this.x = x;\n this.z = z;\n this.y = y;\n return this;\n }\n\n public MotionUpdateEvent setRotation(final float yaw, final float pitch) {\n this.pitch = pitch;\n this.yaw = yaw;\n return this;\n }\n\n public MotionUpdateEvent setRotation(final Rotation rotation) {\n return this.setRotation(rotation.getYaw(), rotation.getPitch());\n }\n\n public MotionUpdateEvent setPosition(final Vec3 vec3) {\n return this.setPosition(vec3.xCoord, vec3.yCoord, vec3.zCoord);\n }\n\n public Rotation getRotation() {\n return new Rotation(this.yaw, this.pitch);\n }\n\n public Vec3 getPosition() {\n return new Vec3(this.x, this.y, this.z);\n }\n\n public MotionUpdateEvent setY(final double y) {\n this.y = y;\n return this;\n }\n\n public MotionUpdateEvent setX(final double x) {\n this.x = x;\n return this;\n }\n\n public MotionUpdateEvent setZ(final double z) {\n this.z = z;\n return this;\n }\n\n public MotionUpdateEvent setYaw(final float yaw) {\n this.yaw = yaw;\n return this;\n }\n\n public MotionUpdateEvent setPitch(final float pitch) {\n this.pitch = pitch;\n return this;\n }\n\n public MotionUpdateEvent setOnGround(final boolean onGround) {\n this.onGround = onGround;\n return this;\n }\n\n public MotionUpdateEvent setSneaking(final boolean sneaking) {\n this.sneaking = sneaking;\n return this;\n }\n\n public MotionUpdateEvent setSprinting(final boolean sprinting) {\n this.sprinting = sprinting;\n return this;\n }\n\n public boolean isPre() {\n return this instanceof Pre;\n }\n\n @Cancelable\n public static class Pre extends MotionUpdateEvent\n {\n public Pre(final double x, final double y, final double z, final float yaw, final float pitch, final boolean onGround, final boolean sprinting, final boolean sneaking) {\n super(x, y, z, yaw, pitch, onGround, sprinting, sneaking);\n }\n }\n\n @Cancelable\n public static class Post extends MotionUpdateEvent\n {\n public Post(final double x, final double y, final double z, final float yaw, final float pitch, final boolean onGround, final boolean sprinting, final boolean sneaking) {\n super(x, y, z, yaw, pitch, onGround, sprinting, sneaking);\n }\n\n public Post(final MotionUpdateEvent event) {\n super(event.x, event.y, event.z, event.yaw, event.pitch, event.onGround, event.sprinting, event.sneaking);\n }\n }\n}" }, { "identifier": "Module", "path": "Client/src/main/java/me/kyroclient/modules/Module.java", "snippet": "public class Module {\n @Expose\n @SerializedName(\"name\")\n public String name;\n @Expose\n @SerializedName(\"toggled\")\n private boolean toggled;\n @Expose\n @SerializedName(\"keyCode\")\n private int keycode;\n private final Category category;\n public boolean extended;\n @Expose\n @SerializedName(\"settings\")\n public ConfigManager.ConfigSetting[] cfgSettings;\n private boolean devOnly;\n public final MilliTimer toggledTime;\n public final List<Setting> settings;\n\n public Module(final String name, final int keycode, final Category category) {\n this.toggledTime = new MilliTimer();\n this.settings = new ArrayList<Setting>();\n this.name = name;\n this.keycode = keycode;\n this.category = category;\n }\n\n public Module(final String name, final Category category) {\n this(name, 0, category);\n }\n\n public boolean isToggled() {\n return this.toggled;\n }\n\n public void toggle() {\n this.setToggled(!this.toggled);\n }\n\n public void onEnable() {\n }\n public void assign()\n {\n\n }\n\n public void onSave() {\n }\n\n public String getSuffix()\n {\n return null;\n }\n\n public void addSetting(final Setting setting) {\n this.getSettings().add(setting);\n }\n\n public void addSettings(final Setting... settings) {\n for (final Setting setting : settings) {\n this.addSetting(setting);\n }\n }\n\n public Category getCategory() {\n return this.category;\n }\n\n public String getName() {\n return this.name;\n }\n\n public boolean isPressed() {\n return this.keycode != 0 && Keyboard.isKeyDown(this.keycode);\n }\n\n public int getKeycode() {\n return this.keycode;\n }\n\n public void setKeycode(final int keycode) {\n this.keycode = keycode;\n }\n\n public List<Setting> getSettings() {\n return this.settings;\n }\n\n public static List<Module> getModulesByCategory(final Category c) {\n return (List<Module>) KyroClient.moduleManager.getModules().stream().filter(module -> module.category == c).collect(Collectors.toList());\n }\n\n /*public static <T> T getModule(final Class<T> module) {\n for (final Module m : KyroClient.modules) {\n if (m.getClass().equals(module)) {\n return (T)m;\n }\n }\n return null;\n }\n\n public static Module getModule(final Predicate<Module> predicate) {\n for (final Module m : KyroClient.modules) {\n if (predicate.test(m)) {\n return m;\n }\n }\n return null;\n }\n\n public static Module getModule(final String string) {\n for (final Module m : KyroClient.modules) {\n if (m.getName().equalsIgnoreCase(string)) {\n return m;\n }\n }\n return null;\n }*/\n\n public void setToggled(final boolean toggled) {\n if (this.toggled != toggled) {\n this.toggled = toggled;\n this.toggledTime.reset();\n if (toggled) {\n this.onEnable();\n }\n else {\n this.onDisable();\n }\n }\n }\n\n public String suffix()\n {\n return \"\";\n }\n\n public void onDisable() {\n }\n\n public void setDevOnly(final boolean devOnly) {\n this.devOnly = devOnly;\n }\n\n public boolean isDevOnly() {\n return this.devOnly;\n }\n\n protected static void sendMessage(final String message) {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n public enum Category\n {\n CRIMSONISLE(\"Crimson Isle\"),\n GARDEN(\"Garden\"),\n RIFT(\"Rift\"),\n DUNGEONS(\"Dungeons\"),\n PLAYER(\"Player\"),\n RENDER(\"Render\"),\n COMBAT(\"Combat\"),\n MISC(\"Misc\"),\n DIANA(\"Diana\"),\n MINING(\"Mining\"),\n CLIENT(\"Client\");\n\n public String name;\n\n private Category(final String name) {\n this.name = name;\n }\n }\n}" }, { "identifier": "BooleanSetting", "path": "Client/src/main/java/me/kyroclient/settings/BooleanSetting.java", "snippet": "public class BooleanSetting extends Setting\n{\n @Expose\n @SerializedName(\"value\")\n private boolean enabled;\n\n public BooleanSetting(final String name, final boolean enabled) {\n super(name);\n this.enabled = enabled;\n }\n\n public BooleanSetting(final String name, final boolean enabled, final Predicate<Boolean> isHidden) {\n super(name, isHidden);\n this.enabled = enabled;\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setEnabled(final boolean enabled) {\n this.enabled = enabled;\n }\n\n public void toggle() {\n this.setEnabled(!this.isEnabled());\n }\n}" }, { "identifier": "ModeSetting", "path": "Client/src/main/java/me/kyroclient/settings/ModeSetting.java", "snippet": "public class ModeSetting extends Setting\n{\n @Expose\n @SerializedName(\"value\")\n private String selected;\n private int index;\n private List<String> modes;\n private String defaultSelected;\n\n public ModeSetting(final String name, final String defaultSelected, final String... options) {\n super(name);\n this.defaultSelected = defaultSelected;\n this.modes = Arrays.asList(options);\n this.index = this.modes.indexOf(defaultSelected);\n this.selected = this.modes.get(this.index);\n }\n\n public ModeSetting(final String name, final Predicate<Boolean> isHidden, final String defaultSelected, final String... options) {\n super(name, isHidden);\n this.defaultSelected = defaultSelected;\n this.modes = Arrays.asList(options);\n this.index = this.modes.indexOf(defaultSelected);\n this.selected = this.modes.get(this.index);\n }\n\n public String getSelected() {\n return this.selected;\n }\n\n public void setSelected(final String selected) {\n this.selected = selected;\n this.index = this.modes.indexOf(selected);\n }\n\n public boolean is(final String mode) {\n return mode.equals(this.selected);\n }\n\n public int getIndex() {\n return this.index;\n }\n\n public void setIndex(final int index) {\n this.index = index;\n this.selected = this.modes.get(index);\n }\n\n public List<String> getModes() {\n return this.modes;\n }\n\n public void setModes(final List<String> modes) {\n this.modes = modes;\n }\n\n public void cycle(final int key) {\n switch (key) {\n case 0: {\n if (this.index < this.modes.size() - 1) {\n ++this.index;\n this.selected = this.modes.get(this.index);\n break;\n }\n if (this.index >= this.modes.size() - 1) {\n this.index = 0;\n this.selected = this.modes.get(0);\n break;\n }\n break;\n }\n case 1: {\n if (this.index > 0) {\n --this.index;\n this.selected = this.modes.get(this.index);\n break;\n }\n this.index = this.modes.size() - 1;\n this.selected = this.modes.get(this.index);\n break;\n }\n default: {\n this.index = this.modes.indexOf(this.defaultSelected);\n this.selected = this.modes.get(this.index);\n break;\n }\n }\n }\n}" }, { "identifier": "NumberSetting", "path": "Client/src/main/java/me/kyroclient/settings/NumberSetting.java", "snippet": "public class NumberSetting extends Setting\n{\n double min;\n double max;\n double increment;\n @Expose\n @SerializedName(\"value\")\n private double value;\n\n public NumberSetting(final String name, final double defaultValue, final double minimum, final double maximum, final double increment) {\n super(name);\n this.value = defaultValue;\n this.min = minimum;\n this.max = maximum;\n this.increment = increment;\n }\n\n public NumberSetting(final String name, final double defaultValue, final double min, final double max, final double increment, final Predicate<Boolean> isHidden) {\n super(name, isHidden);\n this.value = defaultValue;\n this.min = min;\n this.max = max;\n this.increment = increment;\n }\n\n public static double clamp(double value, final double min, final double max) {\n value = Math.max(min, value);\n value = Math.min(max, value);\n return value;\n }\n\n public double getValue() {\n return this.value;\n }\n\n public void setValue(double value) {\n value = clamp(value, this.getMin(), this.getMax());\n value = Math.round(value * (1.0 / this.getIncrement())) / (1.0 / this.getIncrement());\n this.value = value;\n }\n\n public void set(final double value) {\n this.value = value;\n }\n\n public double getMin() {\n return this.min;\n }\n\n public void setMin(final double min) {\n this.min = min;\n }\n\n public double getMax() {\n return this.max;\n }\n\n public void setMax(final double max) {\n this.max = max;\n }\n\n public double getIncrement() {\n return this.increment;\n }\n\n public void setIncrement(final double increment) {\n this.increment = increment;\n }\n}" }, { "identifier": "MilliTimer", "path": "Client/src/main/java/me/kyroclient/util/MilliTimer.java", "snippet": "public class MilliTimer\n{\n private long time;\n\n public MilliTimer() {\n this.reset();\n }\n\n public long getTime() {\n return this.time;\n }\n\n public long getTimePassed() {\n return System.currentTimeMillis() - this.time;\n }\n\n public boolean hasTimePassed(final long milliseconds) {\n return System.currentTimeMillis() - this.time >= milliseconds;\n }\n\n public void reset() {\n this.time = System.currentTimeMillis();\n }\n\n public void reset(final long time) {\n this.time = System.currentTimeMillis() - time;\n }\n public void setTime(long time)\n {\n this.time = time;\n }\n}" }, { "identifier": "MovementUtils", "path": "Client/src/main/java/me/kyroclient/util/MovementUtils.java", "snippet": "public class MovementUtils\n{\n public static MilliTimer strafeTimer;\n\n public static float getSpeed() {\n return (float)Math.sqrt(KyroClient.mc.thePlayer.motionX * KyroClient.mc.thePlayer.motionX + KyroClient.mc.thePlayer.motionZ * KyroClient.mc.thePlayer.motionZ);\n }\n\n public static float getSpeed(final double x, final double z) {\n return (float)Math.sqrt(x * x + z * z);\n }\n\n public static void strafe() {\n strafe(getSpeed());\n }\n\n public static boolean isMoving() {\n return KyroClient.mc.thePlayer.moveForward != 0.0f || KyroClient.mc.thePlayer.moveStrafing != 0.0f;\n }\n\n public static boolean hasMotion() {\n return KyroClient.mc.thePlayer.motionX != 0.0 && KyroClient.mc.thePlayer.motionZ != 0.0 && KyroClient.mc.thePlayer.motionY != 0.0;\n }\n\n public static boolean isOnGround(final double height) {\n return !KyroClient.mc.theWorld.getCollidingBoundingBoxes((Entity)KyroClient.mc.thePlayer, KyroClient.mc.thePlayer.getEntityBoundingBox().offset(0.0, -height, 0.0)).isEmpty();\n }\n\n public static void strafe(final double speed) {\n if (!isMoving()) {\n return;\n }\n final double yaw = getDirection();\n KyroClient.mc.thePlayer.motionX = -Math.sin(yaw) * speed;\n KyroClient.mc.thePlayer.motionZ = Math.cos(yaw) * speed;\n MovementUtils.strafeTimer.reset();\n }\n\n public static void strafe(final float speed, final float yaw) {\n if (!isMoving() || !MovementUtils.strafeTimer.hasTimePassed(150L)) {\n return;\n }\n KyroClient.mc.thePlayer.motionX = -Math.sin(Math.toRadians(yaw)) * speed;\n KyroClient.mc.thePlayer.motionZ = Math.cos(Math.toRadians(yaw)) * speed;\n MovementUtils.strafeTimer.reset();\n }\n\n public static void forward(final double length) {\n final double yaw = Math.toRadians(KyroClient.mc.thePlayer.rotationYaw);\n KyroClient.mc.thePlayer.setPosition(KyroClient.mc.thePlayer.posX + -Math.sin(yaw) * length, KyroClient.mc.thePlayer.posY, KyroClient.mc.thePlayer.posZ + Math.cos(yaw) * length);\n }\n\n public static double getDirection() {\n return Math.toRadians(getYaw());\n }\n\n public static void setMotion(final MoveEvent em, final double speed) {\n double forward = KyroClient.mc.thePlayer.movementInput.moveForward;\n double strafe = KyroClient.mc.thePlayer.movementInput.moveStrafe;\n float yaw = ((Aura.target != null && KyroClient.aura.movementFix.isEnabled())) ? RotationUtils.getRotations(Aura.target).getYaw() : KyroClient.mc.thePlayer.rotationYaw;\n if (forward == 0.0 && strafe == 0.0) {\n KyroClient.mc.thePlayer.motionX = 0.0;\n KyroClient.mc.thePlayer.motionZ = 0.0;\n if (em != null) {\n em.setX(0.0);\n em.setZ(0.0);\n }\n }\n else {\n if (forward != 0.0) {\n if (strafe > 0.0) {\n yaw += ((forward > 0.0) ? -45 : 45);\n }\n else if (strafe < 0.0) {\n yaw += ((forward > 0.0) ? 45 : -45);\n }\n strafe = 0.0;\n if (forward > 0.0) {\n forward = 1.0;\n }\n else if (forward < 0.0) {\n forward = -1.0;\n }\n }\n final double cos = Math.cos(Math.toRadians(yaw + 90.0f));\n final double sin = Math.sin(Math.toRadians(yaw + 90.0f));\n KyroClient.mc.thePlayer.motionX = forward * speed * cos + strafe * speed * sin;\n KyroClient.mc.thePlayer.motionZ = forward * speed * sin - strafe * speed * cos;\n if (em != null) {\n em.setX(KyroClient.mc.thePlayer.motionX);\n em.setZ(KyroClient.mc.thePlayer.motionZ);\n }\n }\n }\n\n public static float getYaw() {\n float yaw = ((Aura.target != null && KyroClient.aura.movementFix.isEnabled())) ? RotationUtils.getRotations(Aura.target).getYaw() : KyroClient.mc.thePlayer.rotationYaw;\n if (KyroClient.mc.thePlayer.moveForward < 0.0f) {\n yaw += 180.0f;\n }\n float forward = 1.0f;\n if (KyroClient.mc.thePlayer.moveForward < 0.0f) {\n forward = -0.5f;\n }\n else if (KyroClient.mc.thePlayer.moveForward > 0.0f) {\n forward = 0.5f;\n }\n if (KyroClient.mc.thePlayer.moveStrafing > 0.0f) {\n yaw -= 90.0f * forward;\n }\n if (KyroClient.mc.thePlayer.moveStrafing < 0.0f) {\n yaw += 90.0f * forward;\n }\n return yaw;\n }\n\n static {\n MovementUtils.strafeTimer = new MilliTimer();\n }\n}" } ]
import me.kyroclient.KyroClient; import me.kyroclient.events.MotionUpdateEvent; import me.kyroclient.modules.Module; import me.kyroclient.settings.BooleanSetting; import me.kyroclient.settings.ModeSetting; import me.kyroclient.settings.NumberSetting; import me.kyroclient.util.MilliTimer; import me.kyroclient.util.MovementUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemSword; import net.minecraft.network.Packet; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
6,618
package me.kyroclient.modules.combat; public class AutoBlock extends Module {
package me.kyroclient.modules.combat; public class AutoBlock extends Module {
public ModeSetting mode;
4
2023-10-15 16:24:51+00:00
8k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/components/items/ItemComponentTest.java
[ { "identifier": "GameExtension", "path": "source/core/src/test/com/csse3200/game/extensions/GameExtension.java", "snippet": "public class GameExtension implements AfterEachCallback, BeforeAllCallback {\n\tprivate Application game;\n\n\t@Override\n\tpublic void beforeAll(ExtensionContext context) {\n\t\t// 'Headless' back-end, so no rendering happens\n\t\tgame = new HeadlessApplication(new ApplicationAdapter() {\n\t\t});\n\n\t\t// Mock any calls to OpenGL\n\t\tGdx.gl20 = Mockito.mock(GL20.class);\n\t\tGdx.gl = Gdx.gl20;\n\t}\n\n\t@Override\n\tpublic void afterEach(ExtensionContext context) {\n\t\t// Clear the global state from the service locator\n\t\tServiceLocator.clear();\n\t}\n}" }, { "identifier": "ResourceService", "path": "source/core/src/main/com/csse3200/game/services/ResourceService.java", "snippet": "public class ResourceService implements Disposable {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ResourceService.class);\n\tprivate final AssetManager assetManager;\n\n\tpublic ResourceService() {\n\t\tthis(new AssetManager());\n\t}\n\n\t/**\n\t * Initialise this ResourceService to use the provided AssetManager.\n\t *\n\t * @param assetManager AssetManager to use in this service.\n\t * @requires assetManager != null\n\t */\n\tpublic ResourceService(AssetManager assetManager) {\n\t\tthis.assetManager = assetManager;\n\t}\n\n\t/**\n\t * Load an asset from a file.\n\t *\n\t * @param filename Asset path\n\t * @param type Class to load into\n\t * @param <T> Type of class to load into\n\t * @return Instance of class loaded from path\n\t * @see AssetManager#get(String, Class)\n\t */\n\tpublic <T> T getAsset(String filename, Class<T> type) {\n\t\treturn assetManager.get(filename, type);\n\t}\n\n\t/**\n\t * Check if an asset has been loaded already\n\t *\n\t * @param resourceName path of the asset\n\t * @param type Class type of the asset\n\t * @param <T> Type of the asset\n\t * @return true if asset has been loaded, false otherwise\n\t * @see AssetManager#contains(String)\n\t */\n\tpublic <T> boolean containsAsset(String resourceName, Class<T> type) {\n\t\treturn assetManager.contains(resourceName, type);\n\t}\n\n\t/**\n\t * Returns the loading completion progress as a percentage.\n\t *\n\t * @return progress\n\t */\n\tpublic int getProgress() {\n\t\treturn (int) (assetManager.getProgress() * 100);\n\t}\n\n\t/**\n\t * Blocking call to load all assets.\n\t *\n\t * @see AssetManager#finishLoading()\n\t */\n\tpublic void loadAll() {\n\t\tlogger.debug(\"Loading all assets\");\n\t\ttry {\n\t\t\tassetManager.finishLoading();\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Loads assets for the specified duration in milliseconds.\n\t *\n\t * @param duration duration to load for\n\t * @return finished loading\n\t * @see AssetManager#update(int)\n\t */\n\tpublic boolean loadForMillis(int duration) {\n\t\tlogger.debug(\"Loading assets for {} ms\", duration);\n\t\ttry {\n\t\t\treturn assetManager.update(duration);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t\treturn assetManager.isFinished();\n\t}\n\n\t/**\n\t * Clears all loaded assets and assets in the preloading queue.\n\t *\n\t * @see AssetManager#clear()\n\t */\n\tpublic void clearAllAssets() {\n\t\tlogger.debug(\"Clearing all assets\");\n\t\tassetManager.clear();\n\t}\n\n\t/**\n\t * Loads a single asset into the asset manager.\n\t *\n\t * @param assetName asset name\n\t * @param type asset type\n\t * @param <T> type\n\t */\n\tprivate <T> void loadAsset(String assetName, Class<T> type) {\n\t\tlogger.debug(\"Loading {}: {}\", type.getSimpleName(), assetName);\n\t\ttry {\n\t\t\tassetManager.load(assetName, type);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Could not load {}: {}\", type.getSimpleName(), assetName);\n\t\t}\n\t}\n\n\t/**\n\t * Loads multiple assets into the asset manager.\n\t *\n\t * @param assetNames list of asset names\n\t * @param type asset type\n\t * @param <T> type\n\t */\n\tprivate <T> void loadAssets(String[] assetNames, Class<T> type) {\n\t\tfor (String resource : assetNames) {\n\t\t\tloadAsset(resource, type);\n\t\t}\n\t}\n\n\t/**\n\t * Loads a list of texture assets into the asset manager.\n\t *\n\t * @param textureNames texture filenames\n\t */\n\tpublic void loadTextures(String[] textureNames) {\n\t\tloadAssets(textureNames, Texture.class);\n\t}\n\n\t/**\n\t * Loads a list of texture atlas assets into the asset manager.\n\t *\n\t * @param textureAtlasNames texture atlas filenames\n\t */\n\tpublic void loadTextureAtlases(String[] textureAtlasNames) {\n\t\tloadAssets(textureAtlasNames, TextureAtlas.class);\n\t}\n\n\t/**\n\t * Loads a list of sounds into the asset manager.\n\t *\n\t * @param soundNames sound filenames\n\t */\n\tpublic void loadSounds(String[] soundNames) {\n\t\tloadAssets(soundNames, Sound.class);\n\t}\n\n\t/**\n\t * Loads a list of music assets into the asset manager.\n\t *\n\t * @param musicNames music filenames\n\t */\n\tpublic void loadMusic(String[] musicNames) {\n\t\tloadAssets(musicNames, Music.class);\n\t}\n\n\t/**\n\t * Loads a list of particle effect assets into the asset manager\n\t *\n\t * @param particleNames particle effect filenames\n\t */\n\tpublic void loadParticleEffects(String[] particleNames) {\n\t\tloadAssets(particleNames, ParticleEffect.class);\n\t}\n\n\tpublic void loadSkins(String[] skinNames) {\n\t\tloadAssets(skinNames, Skin.class);\n\t}\n\n\t/**\n\t * Disposes of assets and all of their dependencies from the resource manager\n\t *\n\t * @param assetNames list of asset names to dispose of\n\t */\n\tpublic void unloadAssets(String[] assetNames) {\n\t\tfor (String assetName : assetNames) {\n\t\t\tlogger.debug(\"Unloading {}\", assetName);\n\t\t\ttry {\n\t\t\t\tassetManager.unload(assetName);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\"Could not unload {}\", assetName);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Disposes of the resource service, clearing the asset manager which clears and disposes of all assets and clears\n\t * the preloading queue\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tassetManager.clear();\n\t}\n}" }, { "identifier": "ServiceLocator", "path": "source/core/src/main/com/csse3200/game/services/ServiceLocator.java", "snippet": "public class ServiceLocator {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ServiceLocator.class);\n\tprivate static EntityService entityService;\n\tprivate static RenderService renderService;\n\tprivate static PhysicsService physicsService;\n\tprivate static InputService inputService;\n\tprivate static ResourceService resourceService;\n\tprivate static TimeService timeService;\n\tprivate static GameTime timeSource;\n\tprivate static GameArea gameArea;\n\tprivate static LightService lightService;\n\tprivate static GameAreaDisplay pauseMenuArea;\n\tprivate static GameAreaDisplay craftArea;\n\tprivate static GdxGame game;\n\tprivate static InventoryDisplayManager inventoryDisplayManager;\n\tprivate static CameraComponent cameraComponent;\n\tprivate static SaveLoadService saveLoadService;\n\tprivate static MissionManager missions;\n\tprivate static PlanetOxygenService planetOxygenService;\n\tprivate static SoundService soundService;\n\tprivate static UIService uiService;\n\n\tprivate static PlantCommandService plantCommandService;\n\tprivate static PlayerHungerService playerHungerService;\n\n\tprivate static PlayerMapService playerMapService;\n\n\tprivate static PlantInfoService plantInfoService;\n\tprivate static boolean cutSceneRunning; // true for running and false otherwise\n\n\tprivate static ParticleService particleService;\n\n\tpublic static PlantCommandService getPlantCommandService() {\n\t\treturn plantCommandService;\n\t}\n\n\tpublic static PlantInfoService getPlantInfoService() {\n\t\treturn plantInfoService;\n\t}\n\n\tpublic static boolean god = false;\n\n\tpublic static GameArea getGameArea() {\n\t\treturn gameArea;\n\t}\n\n\tpublic static CameraComponent getCameraComponent() {\n\t\treturn cameraComponent;\n\t}\n\n\tpublic static EntityService getEntityService() {\n\t\treturn entityService;\n\t}\n\n\tpublic static RenderService getRenderService() {\n\t\treturn renderService;\n\t}\n\n\tpublic static PhysicsService getPhysicsService() {\n\t\treturn physicsService;\n\t}\n\n\tpublic static InputService getInputService() {\n\t\treturn inputService;\n\t}\n\n\tpublic static ResourceService getResourceService() {\n\t\treturn resourceService;\n\t}\n\n\tpublic static GameTime getTimeSource() {\n\t\treturn timeSource;\n\t}\n\n\tpublic static TimeService getTimeService() {\n\t\treturn timeService;\n\t}\n\n\tpublic static LightService getLightService() {\n\t\treturn lightService;\n\t}\n\n\tpublic static MissionManager getMissionManager() {\n\t\treturn missions;\n\t}\n\n\tpublic static PlanetOxygenService getPlanetOxygenService() {\n\t\treturn planetOxygenService;\n\t}\n\n\tpublic static PlayerHungerService getPlayerHungerService() {\n\t\treturn playerHungerService;\n\t}\n\n\tpublic static PlayerMapService getPlayerMapService() {\n\t\treturn playerMapService;\n\t}\n\n\tpublic static SaveLoadService getSaveLoadService() {\n\t\treturn saveLoadService;\n\t}\n\n\tpublic static SoundService getSoundService() {\n\t\treturn soundService;\n\t}\n\n\tpublic static UIService getUIService() {\n\t\treturn uiService;\n\t}\n\n\tpublic static ParticleService getParticleService() {\n\t\treturn particleService;\n\t}\n\n\t/**\n\t * Sets the cutscene status to either running or not running.\n\t *\n\t * @param isRunning true if cutscene is running, false otherwise\n\t */\n\tpublic static void setCutSceneRunning(boolean isRunning) {\n\t\tcutSceneRunning = isRunning;\n\t}\n\n\t/**\n\t * Gets the cutscene status.\n\t *\n\t * @return true if cutscene is running, false otherwise\n\t */\n\tpublic static boolean getCutSceneStatus() {\n\t\treturn cutSceneRunning;\n\t}\n\n\tpublic static void registerGameArea(GameArea area) {\n\t\tlogger.debug(\"Registering game area {}\", area);\n\t\tgameArea = area;\n\t}\n\n\tpublic static void registerCameraComponent(CameraComponent camera) {\n\t\tlogger.debug(\"Registering game area {}\", camera);\n\t\tcameraComponent = camera;\n\t}\n\n\tpublic static void registerEntityService(EntityService service) {\n\t\tlogger.debug(\"Registering entity service {}\", service);\n\t\tentityService = service;\n\t}\n\n\tpublic static void registerRenderService(RenderService service) {\n\t\tlogger.debug(\"Registering render service {}\", service);\n\t\trenderService = service;\n\t}\n\n\tpublic static void registerPhysicsService(PhysicsService service) {\n\t\tlogger.debug(\"Registering physics service {}\", service);\n\t\tphysicsService = service;\n\t}\n\n\tpublic static void registerTimeService(TimeService service) {\n\t\tlogger.debug(\"Registering time service {}\", service);\n\t\ttimeService = service;\n\t}\n\n\tpublic static void registerInputService(InputService source) {\n\t\tlogger.debug(\"Registering input service {}\", source);\n\t\tinputService = source;\n\t}\n\n\tpublic static void registerResourceService(ResourceService source) {\n\t\tlogger.debug(\"Registering resource service {}\", source);\n\t\tresourceService = source;\n\t}\n\n\tpublic static void registerTimeSource(GameTime source) {\n\t\tlogger.debug(\"Registering time source {}\", source);\n\t\ttimeSource = source;\n\t}\n\n\tpublic static void registerMissionManager(MissionManager source) {\n\t\tlogger.debug(\"Registering mission manager {}\", source);\n\t\tmissions = source;\n\t}\n\n\tpublic static void registerUIService(UIService source) {\n\t\tlogger.debug(\"Registering UI service {}\", source);\n\t\tuiService = source;\n\t}\n\n\tpublic static void registerPlanetOxygenService(PlanetOxygenService source) {\n\t\tlogger.debug(\"Registering planet oxygen service {}\", source);\n\t\tplanetOxygenService = source;\n\t}\n\n\n\tpublic static void registerPlayerHungerService(PlayerHungerService source) {\n\t\tlogger.debug(\"Registering player hunger service {}\", source);\n\t\tplayerHungerService = source;\n\t}\n\n\tpublic static void registerPlayerMapService(PlayerMapService source) {\n\t\tlogger.debug(\"Registering player map service {}\", source);\n\t\tplayerMapService = source;\n\t}\n\n\tpublic static void registerPlantCommandService(PlantCommandService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantCommandService = source;\n\t}\n\n\tpublic static void registerPlantInfoService(PlantInfoService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantInfoService = source;\n\t}\n\n\tpublic static void registerLightService(LightService source) {\n\t\tlogger.debug(\"Registering light service {}\", source);\n\t\tlightService = source;\n\t}\n\n\tpublic static void registerInventoryDisplayManager(InventoryDisplayManager source) {\n\t\tlogger.debug(\"Registering inventory display manager {}\", source);\n\t\tinventoryDisplayManager = source;\n\t}\n\n\tpublic static void registerParticleService(ParticleService source) {\n\t\tparticleService = source;\n\t}\n\n\t/**\n\t * Registers the save/load service.\n\t *\n\t * @param source the service to register\n\t */\n\tpublic static void registerSaveLoadService(SaveLoadService source) {\n\t\tlogger.debug(\"Registering Save/Load service {}\", source);\n\t\tsaveLoadService = source;\n\t}\n\n\tpublic static void registerSoundService(SoundService source) {\n\t\tlogger.debug(\"Registering sound service {}\", source);\n\t\tsoundService = source;\n\t}\n\n\t/**\n\t * Clears all registered services.\n\t * Do not clear saveLoadService\n\t */\n\tpublic static void clear() {\n\t\tentityService = null;\n\t\trenderService = null;\n\t\tphysicsService = null;\n\t\ttimeSource = null;\n\t\tinputService = null;\n\t\tresourceService = null;\n\t\tgameArea = null;\n\t\tsoundService = null;\n\t\tlightService = null;\n\t\tparticleService = null;\n\t\ttimeService = null;\n\t\tuiService = null;\n\t}\n\n\tprivate ServiceLocator() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n\tpublic static void registerPauseArea(GameAreaDisplay area) {\n\t\tpauseMenuArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getPauseMenuArea() {\n\t\treturn pauseMenuArea;\n\t}\n\n\tpublic static InventoryDisplayManager getInventoryDisplayManager() {\n\t\treturn inventoryDisplayManager;\n\t}\n\n\tpublic static void registerCraftArea(GameAreaDisplay area) {\n\t\tcraftArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getCraftArea() {\n\t\treturn craftArea;\n\t}\n\n\tpublic static void registerGame(GdxGame gameVar) {\n\t\tgame = gameVar;\n\t}\n\n\tpublic static GdxGame getGame() {\n\t\treturn game;\n\t}\n\n\n}" } ]
import com.badlogic.gdx.graphics.Texture; import com.csse3200.game.extensions.GameExtension; import com.csse3200.game.services.ResourceService; import com.csse3200.game.services.ServiceLocator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.*;
3,936
package com.csse3200.game.components.items; @ExtendWith(GameExtension.class) class ItemComponentTest { @BeforeEach void setup() {
package com.csse3200.game.components.items; @ExtendWith(GameExtension.class) class ItemComponentTest { @BeforeEach void setup() {
ServiceLocator.registerResourceService(new ResourceService());
1
2023-10-17 22:34:04+00:00
8k
moeinfatehi/PassiveDigger
src/PassiveDigger/Passive_optionsPanel.java
[ { "identifier": "BurpExtender", "path": "src/burp/BurpExtender.java", "snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public static String project_Name=\"PassiveDigger\";\r\n private static final String project_Version=\"2.0.0\";\r\n \r\n public BurpExtender() {\r\n// this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel();\r\n }\r\n \r\n @Override\r\n public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks)\r\n {\r\n // keep a reference to our callbacks object\r\n this.callbacks = callbacks;\r\n callbacks.registerHttpListener(new PassiveAnalyzer());\r\n output = new PrintWriter(callbacks.getStdout(), true);\r\n // create our UI\r\n SwingUtilities.invokeLater(new Runnable()\r\n {\r\n @Override\r\n public void run()\r\n {\r\n initComponents();\r\n // customize our UI components\r\n callbacks.customizeUiComponent(tab.panel);\r\n \r\n // add the custom tab to Burp's UI\r\n callbacks.addSuiteTab(tab.tb);\r\n callbacks.registerContextMenuFactory(new menuItem());\r\n \r\n }\r\n });\r\n }\r\n \r\n private void initComponents() {\r\n }// </editor-fold>\r\n \r\n public byte[] processProxyMessage(int messageReference, boolean messageIsRequest, String remoteHost, int remotePort, boolean serviceIsHttps, String httpMethod, String url,\r\n String resourceType, String statusCode, String responseContentType, byte message[], int action[])\r\n {\r\n return message;\r\n }\r\n \r\n public static String getProjectName(){\r\n return project_Name;\r\n }\r\n public static String getVersion(){\r\n return project_Version;\r\n }\r\n \r\n}" }, { "identifier": "IHttpRequestResponse", "path": "src/burp/IHttpRequestResponse.java", "snippet": "public interface IHttpRequestResponse\r\n{\r\n /**\r\n * This method is used to retrieve the request message.\r\n *\r\n * @return The request message.\r\n */\r\n byte[] getRequest();\r\n\r\n /**\r\n * This method is used to update the request message.\r\n *\r\n * @param message The new request message.\r\n */\r\n void setRequest(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the response message.\r\n *\r\n * @return The response message.\r\n */\r\n byte[] getResponse();\r\n\r\n /**\r\n * This method is used to update the response message.\r\n *\r\n * @param message The new response message.\r\n */\r\n void setResponse(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated comment for this item,\r\n * if applicable.\r\n *\r\n * @return The user-annotated comment for this item, or null if none is set.\r\n */\r\n String getComment();\r\n\r\n /**\r\n * This method is used to update the user-annotated comment for this item.\r\n *\r\n * @param comment The comment to be assigned to this item.\r\n */\r\n void setComment(String comment);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated highlight for this\r\n * item, if applicable.\r\n *\r\n * @return The user-annotated highlight for this item, or null if none is\r\n * set.\r\n */\r\n String getHighlight();\r\n\r\n /**\r\n * This method is used to update the user-annotated highlight for this item.\r\n *\r\n * @param color The highlight color to be assigned to this item. Accepted\r\n * values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray,\r\n * or a null String to clear any existing highlight.\r\n */\r\n void setHighlight(String color);\r\n\r\n /**\r\n * This method is used to retrieve the HTTP service for this request /\r\n * response.\r\n *\r\n * @return An\r\n * <code>IHttpService</code> object containing details of the HTTP service.\r\n */\r\n IHttpService getHttpService();\r\n\r\n /**\r\n * This method is used to update the HTTP service for this request /\r\n * response.\r\n *\r\n * @param httpService An\r\n * <code>IHttpService</code> object containing details of the new HTTP\r\n * service.\r\n */\r\n void setHttpService(IHttpService httpService);\r\n\r\n}\r" }, { "identifier": "IRequestInfo", "path": "src/burp/IRequestInfo.java", "snippet": "public interface IRequestInfo\r\n{\r\n /**\r\n * Used to indicate that there is no content.\r\n */\r\n static final byte CONTENT_TYPE_NONE = 0;\r\n /**\r\n * Used to indicate URL-encoded content.\r\n */\r\n static final byte CONTENT_TYPE_URL_ENCODED = 1;\r\n /**\r\n * Used to indicate multi-part content.\r\n */\r\n static final byte CONTENT_TYPE_MULTIPART = 2;\r\n /**\r\n * Used to indicate XML content.\r\n */\r\n static final byte CONTENT_TYPE_XML = 3;\r\n /**\r\n * Used to indicate JSON content.\r\n */\r\n static final byte CONTENT_TYPE_JSON = 4;\r\n /**\r\n * Used to indicate AMF content.\r\n */\r\n static final byte CONTENT_TYPE_AMF = 5;\r\n /**\r\n * Used to indicate unknown content.\r\n */\r\n static final byte CONTENT_TYPE_UNKNOWN = -1;\r\n\r\n /**\r\n * This method is used to obtain the HTTP method used in the request.\r\n *\r\n * @return The HTTP method used in the request.\r\n */\r\n String getMethod();\r\n\r\n /**\r\n * This method is used to obtain the URL in the request.\r\n *\r\n * @return The URL in the request.\r\n */\r\n URL getUrl();\r\n\r\n /**\r\n * This method is used to obtain the HTTP headers contained in the request.\r\n *\r\n * @return The HTTP headers contained in the request.\r\n */\r\n List<String> getHeaders();\r\n\r\n /**\r\n * This method is used to obtain the parameters contained in the request.\r\n *\r\n * @return The parameters contained in the request.\r\n */\r\n List<IParameter> getParameters();\r\n\r\n /**\r\n * This method is used to obtain the offset within the request where the\r\n * message body begins.\r\n *\r\n * @return The offset within the request where the message body begins.\r\n */\r\n int getBodyOffset();\r\n\r\n /**\r\n * This method is used to obtain the content type of the message body.\r\n *\r\n * @return An indication of the content type of the message body. Available\r\n * types are defined within this interface.\r\n */\r\n byte getContentType();\r\n}\r" }, { "identifier": "IResponseInfo", "path": "src/burp/IResponseInfo.java", "snippet": "public interface IResponseInfo\r\n{\r\n /**\r\n * This method is used to obtain the HTTP headers contained in the response.\r\n *\r\n * @return The HTTP headers contained in the response.\r\n */\r\n List<String> getHeaders();\r\n\r\n /**\r\n * This method is used to obtain the offset within the response where the\r\n * message body begins.\r\n *\r\n * @return The offset within the response where the message body begins.\r\n */\r\n int getBodyOffset();\r\n\r\n /**\r\n * This method is used to obtain the HTTP status code contained in the\r\n * response.\r\n *\r\n * @return The HTTP status code contained in the response.\r\n */\r\n short getStatusCode();\r\n\r\n /**\r\n * This method is used to obtain details of the HTTP cookies set in the\r\n * response.\r\n *\r\n * @return A list of <code>ICookie</code> objects representing the cookies\r\n * set in the response, if any.\r\n */\r\n List<ICookie> getCookies();\r\n\r\n /**\r\n * This method is used to obtain the MIME type of the response, as stated in\r\n * the HTTP headers.\r\n *\r\n * @return A textual label for the stated MIME type, or an empty String if\r\n * this is not known or recognized. The possible labels are the same as\r\n * those used in the main Burp UI.\r\n */\r\n String getStatedMimeType();\r\n\r\n /**\r\n * This method is used to obtain the MIME type of the response, as inferred\r\n * from the contents of the HTTP message body.\r\n *\r\n * @return A textual label for the inferred MIME type, or an empty String if\r\n * this is not known or recognized. The possible labels are the same as\r\n * those used in the main Burp UI.\r\n */\r\n String getInferredMimeType();\r\n}\r" } ]
import burp.BurpExtender; import burp.IHttpRequestResponse; import burp.IRequestInfo; import burp.IResponseInfo; import java.awt.Color; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.table.DefaultTableModel;
4,978
.addComponent(options_UpdateButton) .addComponent(options_UpdateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void baseReqRespTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_baseReqRespTableMouseClicked if(evt.getClickCount()==2){ try { int ind=baseReqRespTable.getSelectedRow(); reqRespForm.setReqResp(getBaseReqRespList().get(ind)); reqRespForm rrf = new reqRespForm(); rrf.setLocationRelativeTo(null); rrf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); rrf.setVisible(true); } catch (Exception e) { BurpExtender.output.println("*******"+e.toString()); } } }//GEN-LAST:event_baseReqRespTableMouseClicked private void options_clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_clearButtonActionPerformed DefaultTableModel baseReqRespModel=(DefaultTableModel)baseReqRespTable.getModel(); for (int i = 0; i < baseReqRespModel.getRowCount(); i++) { removeRowFromBaseReqRespTable(i); } }//GEN-LAST:event_options_clearButtonActionPerformed private void options_removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_removeButtonActionPerformed int[]rows=baseReqRespTable.getSelectedRows(); BurpExtender.output.println(rows.length); for(int i=rows.length-1;i>=0;i--){ int thisInd=baseReqRespTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table removeRowFromBaseReqRespTable(thisInd); } }//GEN-LAST:event_options_removeButtonActionPerformed private void options_UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_UpdateButtonActionPerformed //Remove Analyser extra datas for (int i = PassiveAnalyzer.vulnerabilityList.size()-1; i>=0;i--) { if(!PassiveAnalyzer.requestIsInScope(PassiveAnalyzer.vulnerabilityList.get(i).reqResp)){ PassiveAnalyzer.removeAnalyzerTableRow(i); } } //Remove Headers extra datas for (int i = Passive_Headers.getHeadersReqRespList().size()-1; i>=0;i--) { if(!PassiveAnalyzer.requestIsInScope(Passive_Headers.getHeadersReqRespList().get(i))){ Passive_Headers.removeHeadersTableRow(i); } } options_UpdateButton.setEnabled(false); options_UpdateLabel.setForeground(new Color(43, 112, 61)); options_UpdateLabel.setText("Updated."); }//GEN-LAST:event_options_UpdateButtonActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed List<String> codeslist=getDisabledRulesList(); RemoveFromAnalyzerBasedOnCodeList(codeslist); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTable baseReqRespTable; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane18; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton options_UpdateButton; private javax.swing.JLabel options_UpdateLabel; private javax.swing.JButton options_clearButton; private javax.swing.JButton options_removeButton; public static javax.swing.JTable options_request_table; public static javax.swing.JTable options_response_table; // End of variables declaration//GEN-END:variables public static List<IHttpRequestResponse> getBaseReqRespList(){ return baseReqRespList; } public static void AddToBaseReqResp(IHttpRequestResponse reqResp){ BurpExtender.output.println("Adding "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()); try { if(targetIsUnique(reqResp)){ BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is unique => Added"); baseReqRespList.add(reqResp); updateBaseReqRespTable(reqResp); Passive_Headers.addToHeadersTable(reqResp); mainPanel.firstLevelTabs.setSelectedIndex(mainPanel.passive_index); updateOptionsTabTitle(); BurpExtender.output.println("New Target size: "+baseReqRespList.size()+" => "+printTargets()); BurpExtender.output.println("##########"); } else{ BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is Repetetive => Not Added!"+" => "+printTargets()); BurpExtender.output.println("##########"); } } catch (Exception e) { BurpExtender.output.print("AddToBaseReqResp Exception"); } } private static void updateBaseReqRespTable(IHttpRequestResponse reqResp) { DefaultTableModel model=(DefaultTableModel)baseReqRespTable.getModel(); String host=reqResp.getHttpService().getHost(); int port=reqResp.getHttpService().getPort();
package PassiveDigger; /* * 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. */ /** * * @author "Moein Fatehi [email protected]" */ public class Passive_optionsPanel extends javax.swing.JPanel { private static String extension_name="Options"; private static boolean updateRequired=false; private static List<IHttpRequestResponse> baseReqRespList=new ArrayList<>(); private static boolean targetIsUnique(IHttpRequestResponse reqResp) { BurpExtender.output.println("Target size: "+baseReqRespList.size()+" => "+printTargets()); for (IHttpRequestResponse rr : baseReqRespList) { BurpExtender.output.println("**Testing if "+rr.getHttpService().getHost()+":"+rr.getHttpService().getPort()+" Equals to "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()); if(reqResp.getHttpService().getHost().equals(rr.getHttpService().getHost())){ if(reqResp.getHttpService().getPort()==rr.getHttpService().getPort()){ return false; } } } return true; } private static String printTargets() { String tar="["; for (IHttpRequestResponse rr : baseReqRespList) { tar=tar+rr.getHttpService().getHost()+":"+rr.getHttpService().getPort()+","; } tar+="]"; return tar; } /** * Creates new form HeadersPanel */ public Passive_optionsPanel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane18 = new javax.swing.JScrollPane(); baseReqRespTable = new javax.swing.JTable(); jLabel9 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); options_removeButton = new javax.swing.JButton(); options_clearButton = new javax.swing.JButton(); options_UpdateButton = new javax.swing.JButton(); options_UpdateLabel = new javax.swing.JLabel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jScrollPane1 = new javax.swing.JScrollPane(); options_request_table = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); options_response_table = new javax.swing.JTable(); jLabel10 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); baseReqRespTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "Host", "Port" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); baseReqRespTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { baseReqRespTableMouseClicked(evt); } }); jScrollPane18.setViewportView(baseReqRespTable); if (baseReqRespTable.getColumnModel().getColumnCount() > 0) { baseReqRespTable.getColumnModel().getColumn(0).setPreferredWidth(45); baseReqRespTable.getColumnModel().getColumn(0).setMaxWidth(55); baseReqRespTable.getColumnModel().getColumn(1).setPreferredWidth(150); baseReqRespTable.getColumnModel().getColumn(1).setMaxWidth(400); baseReqRespTable.getColumnModel().getColumn(2).setPreferredWidth(60); baseReqRespTable.getColumnModel().getColumn(2).setMaxWidth(80); } jLabel9.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 147, 0)); jLabel9.setText("Targets"); jLabel2.setText("(Double click for details)"); options_removeButton.setText("Remove"); options_removeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { options_removeButtonActionPerformed(evt); } }); options_clearButton.setText("Clear"); options_clearButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { options_clearButtonActionPerformed(evt); } }); options_UpdateButton.setText("Update Other Tabs"); options_UpdateButton.setEnabled(false); options_UpdateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { options_UpdateButtonActionPerformed(evt); } }); options_request_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { { new Boolean(true), "Req_01", "Find file upload functionalities"}, { new Boolean(true), "Req_02", "Find serialized data in request"}, { new Boolean(true), "Req_03", "Find base64-Encoded data in request"} }, new String [] { "Enabled", "Code", "Title" } ) { Class[] types = new Class [] { java.lang.Boolean.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { true, false, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(options_request_table); if (options_request_table.getColumnModel().getColumnCount() > 0) { options_request_table.getColumnModel().getColumn(0).setPreferredWidth(100); options_request_table.getColumnModel().getColumn(0).setMaxWidth(100); options_request_table.getColumnModel().getColumn(1).setPreferredWidth(100); options_request_table.getColumnModel().getColumn(1).setMaxWidth(100); } jTabbedPane1.addTab("Request", jScrollPane1); options_response_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { { new Boolean(true), "Resp_01", "Find SQL errors in resposne for SQL injection"}, { new Boolean(true), "Resp_02", "Find Reflected params (Possible XSS or HTML injection)"}, { new Boolean(true), "Resp_03", "Find possible LFI vulnerabilities"}, { new Boolean(true), "Resp_04", "Find sensitive files"}, { new Boolean(true), "Resp_05", "Fingerprint web server/application"}, { new Boolean(true), "Resp_06", "Find directory indexing/browsing"}, { new Boolean(true), "Resp_07", "Find possible Execution After Redirection (EAR)"}, { new Boolean(true), "Resp_08", "Find sensitive data in errors"}, { new Boolean(true), "Resp_09", "Find misconfiguration in Cookie flags"}, { new Boolean(false), "Resp_10", "Find Base64-encoded data in response"}, { new Boolean(true), "Resp_11", "Extract email addresses"}, { new Boolean(false), "Resp_12", "Extract phone numbers"} }, new String [] { "Enabled", "Code", "Title" } ) { Class[] types = new Class [] { java.lang.Boolean.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { true, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(options_response_table); if (options_response_table.getColumnModel().getColumnCount() > 0) { options_response_table.getColumnModel().getColumn(0).setPreferredWidth(100); options_response_table.getColumnModel().getColumn(0).setMaxWidth(100); options_response_table.getColumnModel().getColumn(1).setPreferredWidth(100); options_response_table.getColumnModel().getColumn(1).setMaxWidth(100); } jTabbedPane1.addTab("Response", jScrollPane2); jLabel10.setFont(new java.awt.Font("Ubuntu", 1, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 147, 0)); jLabel10.setText("Analyzer Configuration"); jButton1.setText("Update Analyzer Tab"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) .addGroup(layout.createSequentialGroup() .addComponent(options_UpdateButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(options_UpdateLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(options_removeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(options_clearButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 117, Short.MAX_VALUE))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(options_removeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(options_clearButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(options_UpdateButton) .addComponent(options_UpdateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void baseReqRespTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_baseReqRespTableMouseClicked if(evt.getClickCount()==2){ try { int ind=baseReqRespTable.getSelectedRow(); reqRespForm.setReqResp(getBaseReqRespList().get(ind)); reqRespForm rrf = new reqRespForm(); rrf.setLocationRelativeTo(null); rrf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); rrf.setVisible(true); } catch (Exception e) { BurpExtender.output.println("*******"+e.toString()); } } }//GEN-LAST:event_baseReqRespTableMouseClicked private void options_clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_clearButtonActionPerformed DefaultTableModel baseReqRespModel=(DefaultTableModel)baseReqRespTable.getModel(); for (int i = 0; i < baseReqRespModel.getRowCount(); i++) { removeRowFromBaseReqRespTable(i); } }//GEN-LAST:event_options_clearButtonActionPerformed private void options_removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_removeButtonActionPerformed int[]rows=baseReqRespTable.getSelectedRows(); BurpExtender.output.println(rows.length); for(int i=rows.length-1;i>=0;i--){ int thisInd=baseReqRespTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table removeRowFromBaseReqRespTable(thisInd); } }//GEN-LAST:event_options_removeButtonActionPerformed private void options_UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_options_UpdateButtonActionPerformed //Remove Analyser extra datas for (int i = PassiveAnalyzer.vulnerabilityList.size()-1; i>=0;i--) { if(!PassiveAnalyzer.requestIsInScope(PassiveAnalyzer.vulnerabilityList.get(i).reqResp)){ PassiveAnalyzer.removeAnalyzerTableRow(i); } } //Remove Headers extra datas for (int i = Passive_Headers.getHeadersReqRespList().size()-1; i>=0;i--) { if(!PassiveAnalyzer.requestIsInScope(Passive_Headers.getHeadersReqRespList().get(i))){ Passive_Headers.removeHeadersTableRow(i); } } options_UpdateButton.setEnabled(false); options_UpdateLabel.setForeground(new Color(43, 112, 61)); options_UpdateLabel.setText("Updated."); }//GEN-LAST:event_options_UpdateButtonActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed List<String> codeslist=getDisabledRulesList(); RemoveFromAnalyzerBasedOnCodeList(codeslist); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTable baseReqRespTable; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane18; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton options_UpdateButton; private javax.swing.JLabel options_UpdateLabel; private javax.swing.JButton options_clearButton; private javax.swing.JButton options_removeButton; public static javax.swing.JTable options_request_table; public static javax.swing.JTable options_response_table; // End of variables declaration//GEN-END:variables public static List<IHttpRequestResponse> getBaseReqRespList(){ return baseReqRespList; } public static void AddToBaseReqResp(IHttpRequestResponse reqResp){ BurpExtender.output.println("Adding "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()); try { if(targetIsUnique(reqResp)){ BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is unique => Added"); baseReqRespList.add(reqResp); updateBaseReqRespTable(reqResp); Passive_Headers.addToHeadersTable(reqResp); mainPanel.firstLevelTabs.setSelectedIndex(mainPanel.passive_index); updateOptionsTabTitle(); BurpExtender.output.println("New Target size: "+baseReqRespList.size()+" => "+printTargets()); BurpExtender.output.println("##########"); } else{ BurpExtender.output.println(" "+reqResp.getHttpService().getHost()+":"+reqResp.getHttpService().getPort()+" is Repetetive => Not Added!"+" => "+printTargets()); BurpExtender.output.println("##########"); } } catch (Exception e) { BurpExtender.output.print("AddToBaseReqResp Exception"); } } private static void updateBaseReqRespTable(IHttpRequestResponse reqResp) { DefaultTableModel model=(DefaultTableModel)baseReqRespTable.getModel(); String host=reqResp.getHttpService().getHost(); int port=reqResp.getHttpService().getPort();
IRequestInfo reqInfo=BurpExtender.callbacks.getHelpers().analyzeRequest(reqResp);
2
2023-10-23 12:13:00+00:00
8k
LuckPerms/rest-api-java-client
src/test/java/me/lucko/luckperms/rest/UserServiceTest.java
[ { "identifier": "LuckPermsRestClient", "path": "src/main/java/net/luckperms/rest/LuckPermsRestClient.java", "snippet": "public interface LuckPermsRestClient extends AutoCloseable {\n\n /**\n * Creates a new client builder.\n *\n * @return the new builder\n */\n static Builder builder() {\n return new LuckPermsRestClientImpl.BuilderImpl();\n }\n\n /**\n * Gets the user service.\n *\n * @return the user service\n */\n UserService users();\n\n /**\n * Gets the group service.\n *\n * @return the group service\n */\n GroupService groups();\n\n /**\n * Gets the track service.\n *\n * @return the track service\n */\n TrackService tracks();\n\n /**\n * Gets the action service.\n *\n * @return the action service\n */\n ActionService actions();\n\n /**\n * Gets the misc service.\n *\n * @return the misc service.\n */\n MiscService misc();\n\n /**\n * Close the underlying resources used by the client.\n */\n @Override\n void close();\n\n /**\n * A builder for {@link LuckPermsRestClient}\n */\n interface Builder {\n\n /**\n * Sets the API base URL.\n *\n * @param baseUrl the base url\n * @return this builder\n */\n Builder baseUrl(String baseUrl);\n\n /**\n * Sets the API key for authentication.\n *\n * @param apiKey the api key\n * @return this builder\n */\n Builder apiKey(String apiKey);\n\n /**\n * Builds a client.\n *\n * @return a client\n */\n LuckPermsRestClient build();\n }\n}" }, { "identifier": "Context", "path": "src/main/java/net/luckperms/rest/model/Context.java", "snippet": "public class Context extends AbstractModel {\n private final String key;\n private final String value;\n\n public Context(String key, String value) {\n this.key = key;\n this.value = value;\n }\n\n public String key() {\n return this.key;\n }\n\n public String value() {\n return this.value;\n }\n}" }, { "identifier": "CreateGroupRequest", "path": "src/main/java/net/luckperms/rest/model/CreateGroupRequest.java", "snippet": "public class CreateGroupRequest extends AbstractModel {\n private final String name;\n\n public CreateGroupRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}" }, { "identifier": "CreateTrackRequest", "path": "src/main/java/net/luckperms/rest/model/CreateTrackRequest.java", "snippet": "public class CreateTrackRequest extends AbstractModel {\n private final String name;\n\n public CreateTrackRequest(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n}" }, { "identifier": "CreateUserRequest", "path": "src/main/java/net/luckperms/rest/model/CreateUserRequest.java", "snippet": "public class CreateUserRequest extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n\n public CreateUserRequest(UUID uniqueId, String username) {\n this.uniqueId = uniqueId;\n this.username = username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "DemotionResult", "path": "src/main/java/net/luckperms/rest/model/DemotionResult.java", "snippet": "public class DemotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public DemotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"removed_from_first_group\")\n REMOVED_FROM_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"not_on_track\")\n NOT_ON_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "Group", "path": "src/main/java/net/luckperms/rest/model/Group.java", "snippet": "public class Group extends AbstractModel {\n private final String name;\n private final String displayName;\n private final int weight;\n private final Collection<Node> nodes;\n private final Metadata metadata;\n\n public Group(String name, String displayName, int weight, Collection<Node> nodes, Metadata metadata) {\n this.name = name;\n this.displayName = displayName;\n this.weight = weight;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public String name() {\n return this.name;\n }\n\n public int weight() {\n return this.weight;\n }\n\n public Collection<Node> nodes() {\n return this.nodes;\n }\n\n public String displayName() {\n return this.displayName;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}" }, { "identifier": "Metadata", "path": "src/main/java/net/luckperms/rest/model/Metadata.java", "snippet": "public class Metadata extends AbstractModel {\n private final Map<String, String> meta;\n private final String prefix; // nullable\n private final String suffix; // nullable\n private final String primaryGroup; // nullable\n\n public Metadata(Map<String, String> meta, String prefix, String suffix, String primaryGroup) {\n this.meta = meta;\n this.prefix = prefix;\n this.suffix = suffix;\n this.primaryGroup = primaryGroup;\n }\n\n public Map<String, String> meta() {\n return this.meta;\n }\n\n public String prefix() {\n return this.prefix;\n }\n\n public String suffix() {\n return this.suffix;\n }\n\n public String primaryGroup() {\n return this.primaryGroup;\n }\n}" }, { "identifier": "Node", "path": "src/main/java/net/luckperms/rest/model/Node.java", "snippet": "public class Node extends AbstractModel {\n private final String key;\n private final Boolean value;\n private final Set<Context> context;\n private final Long expiry;\n\n public Node(String key, Boolean value, Set<Context> context, Long expiry) {\n this.key = key;\n this.value = value;\n this.context = context;\n this.expiry = expiry;\n }\n\n public String key() {\n return this.key;\n }\n\n public Boolean value() {\n return this.value;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n\n public Long expiry() {\n return this.expiry;\n }\n}" }, { "identifier": "NodeType", "path": "src/main/java/net/luckperms/rest/model/NodeType.java", "snippet": "public enum NodeType {\n\n @SerializedName(\"regex_permission\")\n REGEX_PERMISSION,\n\n @SerializedName(\"inheritance\")\n INHERITANCE,\n\n @SerializedName(\"prefix\")\n PREFIX,\n\n @SerializedName(\"suffix\")\n SUFFIX,\n\n @SerializedName(\"meta\")\n META,\n\n @SerializedName(\"weight\")\n WEIGHT,\n\n @SerializedName(\"display_name\")\n DISPLAY_NAME;\n\n @Override\n public String toString() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}" }, { "identifier": "PermissionCheckRequest", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckRequest.java", "snippet": "public class PermissionCheckRequest extends AbstractModel {\n private final String permission;\n private final QueryOptions queryOptions; // nullable\n\n public PermissionCheckRequest(String permission, QueryOptions queryOptions) {\n this.permission = permission;\n this.queryOptions = queryOptions;\n }\n\n public String permission() {\n return this.permission;\n }\n\n public QueryOptions queryOptions() {\n return this.queryOptions;\n }\n}" }, { "identifier": "PermissionCheckResult", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckResult.java", "snippet": "public class PermissionCheckResult extends AbstractModel {\n private final Tristate result;\n private final Node node;\n\n public PermissionCheckResult(Tristate result, Node node) {\n this.result = result;\n this.node = node;\n }\n\n public Tristate result() {\n return this.result;\n }\n\n public Node node() {\n return this.node;\n }\n\n public enum Tristate {\n\n @SerializedName(\"true\")\n TRUE,\n\n @SerializedName(\"false\")\n FALSE,\n\n @SerializedName(\"undefined\")\n UNDEFINED\n }\n}" }, { "identifier": "PlayerSaveResult", "path": "src/main/java/net/luckperms/rest/model/PlayerSaveResult.java", "snippet": "public class PlayerSaveResult extends AbstractModel {\n private final Set<Outcome> outcomes;\n private final String previousUsername; // nullable\n private final Set<UUID> otherUniqueIds; // nullable\n\n public PlayerSaveResult(Set<Outcome> outcomes, String previousUsername, Set<UUID> otherUniqueIds) {\n this.outcomes = outcomes;\n this.previousUsername = previousUsername;\n this.otherUniqueIds = otherUniqueIds;\n }\n\n public Set<Outcome> outcomes() {\n return this.outcomes;\n }\n\n public String previousUsername() {\n return this.previousUsername;\n }\n\n public Set<UUID> otherUniqueIds() {\n return this.otherUniqueIds;\n }\n\n public enum Outcome {\n\n @SerializedName(\"clean_insert\")\n CLEAN_INSERT,\n\n @SerializedName(\"no_change\")\n NO_CHANGE,\n\n @SerializedName(\"username_updated\")\n USERNAME_UPDATED,\n\n @SerializedName(\"other_unique_ids_present_for_username\")\n OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME,\n }\n\n}" }, { "identifier": "PromotionResult", "path": "src/main/java/net/luckperms/rest/model/PromotionResult.java", "snippet": "public class PromotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public PromotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"added_to_first_group\")\n ADDED_TO_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"end_of_track\")\n END_OF_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "QueryOptions", "path": "src/main/java/net/luckperms/rest/model/QueryOptions.java", "snippet": "public class QueryOptions extends AbstractModel {\n private final Mode queryMode; // nullable\n private final Set<Flag> flags; // nullable\n private final Set<Context> contexts; // nullable\n\n public QueryOptions(Mode queryMode, Set<Flag> flags, Set<Context> contexts) {\n this.queryMode = queryMode;\n this.flags = flags;\n this.contexts = contexts;\n }\n\n public Mode queryMode() {\n return this.queryMode;\n }\n\n public Set<Flag> flags() {\n return this.flags;\n }\n\n public Set<Context> contexts() {\n return this.contexts;\n }\n\n public enum Mode {\n\n @SerializedName(\"contextual\")\n CONTEXTUAL,\n\n @SerializedName(\"non_contextual\")\n NON_CONTEXTUAL\n }\n\n public enum Flag {\n\n @SerializedName(\"resolve_inheritance\")\n RESOLVE_INHERITANCE,\n\n @SerializedName(\"include_nodes_without_server_context\")\n INCLUDE_NODES_WITHOUT_SERVER_CONTEXT,\n\n @SerializedName(\"include_nodes_without_world_context\")\n INCLUDE_NODES_WITHOUT_WORLD_CONTEXT,\n\n @SerializedName(\"apply_inheritance_nodes_without_server_context\")\n APPLY_INHERITANCE_NODES_WITHOUT_SERVER_CONTEXT,\n\n @SerializedName(\"apply_inheritance_nodes_without_world_context\")\n APPLY_INHERITANCE_NODES_WITHOUT_WORLD_CONTEXT\n }\n}" }, { "identifier": "TemporaryNodeMergeStrategy", "path": "src/main/java/net/luckperms/rest/model/TemporaryNodeMergeStrategy.java", "snippet": "public enum TemporaryNodeMergeStrategy {\n\n @SerializedName(\"add_new_duration_to_existing\")\n ADD_NEW_DURATION_TO_EXISTING,\n\n @SerializedName(\"replace_existing_if_duration_longer\")\n REPLACE_EXISTING_IF_DURATION_LONGER,\n\n @SerializedName(\"none\")\n NONE\n\n}" }, { "identifier": "TrackRequest", "path": "src/main/java/net/luckperms/rest/model/TrackRequest.java", "snippet": "public class TrackRequest extends AbstractModel {\n private final String track;\n private final Set<Context> context;\n\n public TrackRequest(String track, Set<Context> context) {\n this.track = track;\n this.context = context;\n }\n\n public String track() {\n return this.track;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n}" }, { "identifier": "UpdateTrackRequest", "path": "src/main/java/net/luckperms/rest/model/UpdateTrackRequest.java", "snippet": "public class UpdateTrackRequest extends AbstractModel {\n private final List<String> groups;\n\n public UpdateTrackRequest(List<String> groups) {\n this.groups = groups;\n }\n\n public List<String> username() {\n return this.groups;\n }\n}" }, { "identifier": "UpdateUserRequest", "path": "src/main/java/net/luckperms/rest/model/UpdateUserRequest.java", "snippet": "public class UpdateUserRequest extends AbstractModel {\n private final String username;\n\n public UpdateUserRequest(String username) {\n this.username = username;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "User", "path": "src/main/java/net/luckperms/rest/model/User.java", "snippet": "public class User extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n private final List<String> parentGroups;\n private final List<Node> nodes;\n private final Metadata metadata;\n\n public User(UUID uniqueId, String username, List<String> parentGroups, List<Node> nodes, Metadata metadata) {\n this.uniqueId = uniqueId;\n this.username = username;\n this.parentGroups = parentGroups;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public List<String> parentGroups() {\n return this.parentGroups;\n }\n\n public List<Node> nodes() {\n return this.nodes;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}" }, { "identifier": "UserLookupResult", "path": "src/main/java/net/luckperms/rest/model/UserLookupResult.java", "snippet": "public class UserLookupResult extends AbstractModel {\n private final String username;\n private final UUID uniqueId;\n\n public UserLookupResult(String username, UUID uniqueId) {\n this.username = username;\n this.uniqueId = uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n}" }, { "identifier": "UserSearchResult", "path": "src/main/java/net/luckperms/rest/model/UserSearchResult.java", "snippet": "public class UserSearchResult extends AbstractModel {\n private final UUID uniqueId;\n private final Collection<Node> results;\n\n public UserSearchResult(UUID uniqueId, Collection<Node> results) {\n this.uniqueId = uniqueId;\n this.results = results;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public Collection<Node> results() {\n return this.results;\n }\n}" } ]
import net.luckperms.rest.LuckPermsRestClient; import net.luckperms.rest.model.Context; import net.luckperms.rest.model.CreateGroupRequest; import net.luckperms.rest.model.CreateTrackRequest; import net.luckperms.rest.model.CreateUserRequest; import net.luckperms.rest.model.DemotionResult; import net.luckperms.rest.model.Group; import net.luckperms.rest.model.Metadata; import net.luckperms.rest.model.Node; import net.luckperms.rest.model.NodeType; import net.luckperms.rest.model.PermissionCheckRequest; import net.luckperms.rest.model.PermissionCheckResult; import net.luckperms.rest.model.PlayerSaveResult; import net.luckperms.rest.model.PromotionResult; import net.luckperms.rest.model.QueryOptions; import net.luckperms.rest.model.TemporaryNodeMergeStrategy; import net.luckperms.rest.model.TrackRequest; import net.luckperms.rest.model.UpdateTrackRequest; import net.luckperms.rest.model.UpdateUserRequest; import net.luckperms.rest.model.User; import net.luckperms.rest.model.UserLookupResult; import net.luckperms.rest.model.UserSearchResult; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import retrofit2.Response; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue;
5,847
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * 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 me.lucko.luckperms.rest; public class UserServiceTest extends AbstractIntegrationTest { @Test public void testUserCrud() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp.isSuccessful()); assertEquals(201, createResp.code()); PlayerSaveResult result = createResp.body(); assertNotNull(result); // read Response<User> readResp = client.users().get(uuid).execute(); assertTrue(readResp.isSuccessful()); User user = readResp.body(); assertNotNull(user); assertEquals(uuid, user.uniqueId()); assertEquals(username, user.username()); // update Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute(); assertTrue(updateResp.isSuccessful()); // delete Response<Void> deleteResp = client.users().delete(uuid).execute(); assertTrue(deleteResp.isSuccessful()); } @Test public void testUserCreate() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create - clean insert Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp1.isSuccessful()); assertEquals(201, createResp1.code()); PlayerSaveResult result1 = createResp1.body(); assertNotNull(result1); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes()); assertNull(result1.previousUsername()); assertNull(result1.otherUniqueIds()); // create - no change Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp2.isSuccessful()); assertEquals(200, createResp2.code()); PlayerSaveResult result2 = createResp2.body(); assertNotNull(result2); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes()); assertNull(result2.previousUsername()); assertNull(result2.otherUniqueIds()); // create - changed username String otherUsername = randomName(); Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute(); assertTrue(createResp3.isSuccessful()); assertEquals(200, createResp3.code()); PlayerSaveResult result3 = createResp3.body(); assertNotNull(result3); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes()); assertEquals(username, result3.previousUsername()); assertNull(result3.otherUniqueIds()); // create - changed uuid UUID otherUuid = UUID.randomUUID(); Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute(); assertTrue(createResp4.isSuccessful()); assertEquals(201, createResp4.code()); PlayerSaveResult result4 = createResp4.body(); assertNotNull(result4); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes()); assertNull(result4.previousUsername()); assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds()); } @Test public void testUserList() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user & give it a permission assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful()); Response<Set<UUID>> resp = client.users().list().execute(); assertTrue(resp.isSuccessful()); assertNotNull(resp.body()); assertTrue(resp.body().contains(uuid)); } @Test public void testUserLookup() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // uuid to username Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute(); assertTrue(uuidToUsername.isSuccessful()); assertNotNull(uuidToUsername.body()); assertEquals(username, uuidToUsername.body().username()); // username to uuid Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute(); assertTrue(usernameToUuid.isSuccessful()); assertNotNull(usernameToUuid.body()); assertEquals(uuid, uuidToUsername.body().uniqueId()); // not found assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code()); assertEquals(404, client.users().lookup(randomName()).execute().code()); } @Test public void testUserNodes() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // get user nodes and validate they are as expected List<Node> nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null) ), nodes); long expiryTime = (System.currentTimeMillis() / 1000L) + 60; // add a node assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful()); // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null),
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * 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 me.lucko.luckperms.rest; public class UserServiceTest extends AbstractIntegrationTest { @Test public void testUserCrud() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp.isSuccessful()); assertEquals(201, createResp.code()); PlayerSaveResult result = createResp.body(); assertNotNull(result); // read Response<User> readResp = client.users().get(uuid).execute(); assertTrue(readResp.isSuccessful()); User user = readResp.body(); assertNotNull(user); assertEquals(uuid, user.uniqueId()); assertEquals(username, user.username()); // update Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute(); assertTrue(updateResp.isSuccessful()); // delete Response<Void> deleteResp = client.users().delete(uuid).execute(); assertTrue(deleteResp.isSuccessful()); } @Test public void testUserCreate() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create - clean insert Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp1.isSuccessful()); assertEquals(201, createResp1.code()); PlayerSaveResult result1 = createResp1.body(); assertNotNull(result1); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes()); assertNull(result1.previousUsername()); assertNull(result1.otherUniqueIds()); // create - no change Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp2.isSuccessful()); assertEquals(200, createResp2.code()); PlayerSaveResult result2 = createResp2.body(); assertNotNull(result2); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes()); assertNull(result2.previousUsername()); assertNull(result2.otherUniqueIds()); // create - changed username String otherUsername = randomName(); Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute(); assertTrue(createResp3.isSuccessful()); assertEquals(200, createResp3.code()); PlayerSaveResult result3 = createResp3.body(); assertNotNull(result3); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes()); assertEquals(username, result3.previousUsername()); assertNull(result3.otherUniqueIds()); // create - changed uuid UUID otherUuid = UUID.randomUUID(); Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute(); assertTrue(createResp4.isSuccessful()); assertEquals(201, createResp4.code()); PlayerSaveResult result4 = createResp4.body(); assertNotNull(result4); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes()); assertNull(result4.previousUsername()); assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds()); } @Test public void testUserList() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user & give it a permission assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful()); Response<Set<UUID>> resp = client.users().list().execute(); assertTrue(resp.isSuccessful()); assertNotNull(resp.body()); assertTrue(resp.body().contains(uuid)); } @Test public void testUserLookup() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // uuid to username Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute(); assertTrue(uuidToUsername.isSuccessful()); assertNotNull(uuidToUsername.body()); assertEquals(username, uuidToUsername.body().username()); // username to uuid Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute(); assertTrue(usernameToUuid.isSuccessful()); assertNotNull(usernameToUuid.body()); assertEquals(uuid, uuidToUsername.body().uniqueId()); // not found assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code()); assertEquals(404, client.users().lookup(randomName()).execute().code()); } @Test public void testUserNodes() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // get user nodes and validate they are as expected List<Node> nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null) ), nodes); long expiryTime = (System.currentTimeMillis() / 1000L) + 60; // add a node assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful()); // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null),
new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null),
1
2023-10-22 16:07:30+00:00
8k
EvanAatrox/hubbo
hubbo-config/src/main/java/cn/hubbo/configuration/security/SpringSecurityConfig.java
[ { "identifier": "JWTProperties", "path": "hubbo-common/src/main/java/cn/hubbo/common/domain/to/properties/JWTProperties.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"token\")\n@Data\npublic class JWTProperties {\n\n\n Map<String, Object> header = new HashMap<>();\n\n\n /* 类型 */\n private String type = \"JWT\";\n\n\n /* 使用的加密算法 */\n private String algorithm;\n\n\n /* token的有效期,单位为秒 */\n @DurationUnit(ChronoUnit.SECONDS)\n private Duration duration;\n\n\n /* token加密的密钥 */\n private String secretKey;\n\n @PostConstruct\n public void init() {\n header.put(\"typ\", type);\n header.put(\"alg\", algorithm);\n }\n\n\n}" }, { "identifier": "AccessDecisionManagerImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/AccessDecisionManagerImpl.java", "snippet": "public class AccessDecisionManagerImpl implements AccessDecisionManager {\n\n /**\n * Resolves an access control decision for the passed parameters.\n *\n * @param authentication the caller invoking the method (not null)\n * @param object the secured object being called\n * @param configAttributes the configuration attributes associated with the secured\n * object being invoked\n * @throws AccessDeniedException if access is denied as the authentication does not\n * hold a required authority or ACL privilege\n * @throws InsufficientAuthenticationException if access is denied as the\n * authentication does not provide a sufficient level of trust\n */\n @Override\n public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {\n for (GrantedAuthority authority : authentication.getAuthorities()) {\n System.out.println(authority);\n }\n }\n\n /**\n * Indicates whether this <code>AccessDecisionManager</code> is able to process\n * authorization requests presented with the passed <code>ConfigAttribute</code>.\n * <p>\n * This allows the <code>AbstractSecurityInterceptor</code> to check every\n * configuration attribute can be consumed by the configured\n * <code>AccessDecisionManager</code> and/or <code>RunAsManager</code> and/or\n * <code>AfterInvocationManager</code>.\n * </p>\n *\n * @param attribute a configuration attribute that has been configured against the\n * <code>AbstractSecurityInterceptor</code>\n * @return true if this <code>AccessDecisionManager</code> can support the passed\n * configuration attribute\n */\n @Override\n public boolean supports(ConfigAttribute attribute) {\n return true;\n }\n\n /**\n * Indicates whether the <code>AccessDecisionManager</code> implementation is able to\n * provide access control decisions for the indicated secured object type.\n *\n * @param clazz the class that is being queried\n * @return <code>true</code> if the implementation can process the indicated class\n */\n @Override\n public boolean supports(Class<?> clazz) {\n return true;\n }\n}" }, { "identifier": "CustomFilterInvocationSecurityMetadataSource", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/CustomFilterInvocationSecurityMetadataSource.java", "snippet": "public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {\n\n\n @Override\n public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {\n if (object instanceof FilterInvocation filterInvocation) {\n HttpServletRequest request = filterInvocation.getRequest();\n return SecurityConfig.createList(\"admin\");\n }\n return null;\n }\n\n @Override\n public Collection<ConfigAttribute> getAllConfigAttributes() {\n return null;\n }\n\n @Override\n public boolean supports(Class<?> clazz) {\n return true;\n }\n\n}" }, { "identifier": "DynamicFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/DynamicFilter.java", "snippet": "public class DynamicFilter extends AbstractSecurityInterceptor implements Filter {\n\n private FilterInvocationSecurityMetadataSource invocationSecurityMetadataSource;\n\n\n private AccessDecisionManager accessDecisionManager;\n\n private AntPathMatcher antPathMatcher;\n\n\n public DynamicFilter(FilterInvocationSecurityMetadataSource invocationSecurityMetadataSource, AccessDecisionManager accessDecisionManager) {\n this.invocationSecurityMetadataSource = invocationSecurityMetadataSource;\n this.accessDecisionManager = accessDecisionManager;\n super.setAccessDecisionManager(accessDecisionManager);\n this.antPathMatcher = new AntPathMatcher();\n }\n\n @Override\n public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {\n if (servletRequest instanceof HttpServletRequest request && servletResponse instanceof HttpServletResponse response) {\n FilterInvocation filterInvocation = new FilterInvocation(request, response, filterChain);\n //直接放行OPTIONS 请求\n if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n return;\n }\n // 放行白名单资源\n List<String> ignorePathPatterns = List.of(\"/test/**\", \"/user/**\");\n for (String pattern : ignorePathPatterns) {\n if (antPathMatcher.match(pattern, request.getRequestURI().toString())) {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n return;\n }\n }\n InterceptorStatusToken token = super.beforeInvocation(filterInvocation);\n try {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n } finally {\n super.afterInvocation(token, null);\n }\n\n }\n }\n\n\n @Override\n public Class<?> getSecureObjectClass() {\n return FilterInvocation.class;\n }\n\n\n @Override\n public SecurityMetadataSource obtainSecurityMetadataSource() {\n return invocationSecurityMetadataSource;\n }\n\n\n}" }, { "identifier": "FormAndJsonLoginFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/FormAndJsonLoginFilter.java", "snippet": "@Slf4j\n@SuppressWarnings({\"unused\"})\npublic class FormAndJsonLoginFilter extends UsernamePasswordAuthenticationFilter {\n\n\n private final AuthenticationManager authenticationManager;\n\n\n private final RedisTemplate<String, Object> redisTemplate;\n\n\n private final ValueOperations<String, Object> ops;\n\n\n /* 用户token信息缓存时间 */\n private Duration duration = Duration.ofDays(1);\n\n\n /* Jwt配置信息 */\n private JWTProperties jwtProperties;\n\n public FormAndJsonLoginFilter(AuthenticationManager authenticationManager, RedisTemplate<String, Object> redisTemplate, JWTProperties jwtProperties) {\n super(authenticationManager);\n super.setPostOnly(true);\n super.setFilterProcessesUrl(\"/user/login\");\n this.authenticationManager = authenticationManager;\n this.redisTemplate = redisTemplate;\n this.ops = redisTemplate.opsForValue();\n this.jwtProperties = jwtProperties;\n }\n\n\n /**\n * @param request 请求\n * @param response 响应\n * @return 认证信息\n * @throws AuthenticationException 失败信息,异常的明细详见CSDN 程序三两行的博客描述\n * https://blog.csdn.net/qq_34491508/article/details/126010263\n */\n @Override\n public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {\n String contentType = request.getContentType();\n LoginUserVO userVO = null;\n UsernamePasswordAuthenticationToken authenticationToken = null;\n if (MediaType.APPLICATION_JSON.includes(MediaType.valueOf(contentType))) {\n try {\n userVO = ServletUtils.getRequiredData(request, LoginUserVO.class);\n } catch (Exception ignored) {\n }\n // 校验提交的登录信息是否有效,无效则抛出不充分的认证信息错误\n if (Objects.isNull(userVO) || StringUtils.isBlank(userVO.getUsername()) || StringUtils.isBlank(userVO.getRawPasswd())) {\n throw new InsufficientAuthenticationException(\"登录信息不完整\");\n }\n //TODO 校验验证码是否一致,否则抛出CaptchaNotValidException\n checkCaptchaIsValid(userVO);\n authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(userVO.getUsername(), userVO.getRawPasswd());\n } else {\n String username = ServletUtils.getParameterOrDefault(request, \"username\");\n String rawPasswd = ServletUtils.getParameterOrDefault(request, \"rawPasswd\");\n if (StringUtils.isBlank(username) || StringUtils.isEmpty(rawPasswd)) {\n throw new InsufficientAuthenticationException(\"登录信息不完整\");\n }\n authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(username, rawPasswd);\n }\n this.setDetails(request, authenticationToken);\n return authenticationManager.authenticate(authenticationToken);\n }\n\n /**\n * 认证成功地回调\n *\n * @param request 请求\n * @param response 响应\n * @param chain 过滤器链\n * @param authResult 认证信息\n * @throws IOException 异常信息\n * @throws ServletException 异常信息\n */\n @Override\n protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {\n log.info(\"认证信息{}\", authResult);\n if (authResult instanceof UsernamePasswordAuthenticationToken authenticationToken) {\n if (authenticationToken.getPrincipal() instanceof SecurityUser securityUser) {\n User userDetail = securityUser.getUserDetail();\n ops.set(RedisConstants.USER_TOKEN_PREFIX.concat(userDetail.getUsername()), userDetail, duration);\n String uuid = IdUtil.fastUUID();\n JWTObject jwtObject = JWTTokenBuilder.create()\n .id(uuid)\n .claim(userDetail.getUsername())\n .timeout(jwtProperties.getDuration())\n .sign(jwtProperties.getSecretKey()).build();\n // TODO 将token信息存入redis中,后期token续期需要使用到,即使token的值一直在变化,但是token的uuid应该始终不变了\n ops.set(RedisConstants.USER_TOKEN_CACHE_PREFIX.concat(uuid), jwtObject.getToken(), duration);\n Result result = new Result(ResponseStatusEnum.SUCCESS).add(\"token\", jwtObject.getToken());\n ServletUtils.reposeObjectWithJson(response, result);\n }\n } else {\n chain.doFilter(request, response);\n }\n }\n\n\n /**\n * TODO 校验验证码\n *\n * @param loginUserVO 校验验证码是否一致,否则抛出CaptchaNotValidException\n */\n private void checkCaptchaIsValid(LoginUserVO loginUserVO) {\n\n }\n\n\n}" }, { "identifier": "JwtTokenFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/JwtTokenFilter.java", "snippet": "public class JwtTokenFilter extends OncePerRequestFilter {\n\n\n private RedisTemplate<String, Object> redisTemplate;\n\n private ValueOperations<String, Object> ops;\n\n private JWTProperties jwtProperties;\n\n public JwtTokenFilter(RedisTemplate<String, Object> redisTemplate, JWTProperties jwtProperties) {\n this.redisTemplate = redisTemplate;\n this.ops = redisTemplate.opsForValue();\n this.jwtProperties = jwtProperties;\n }\n\n @Override\n protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {\n String headerValue = request.getHeader(WebConstants.TOKEN_HEADER);\n if (StringUtils.isNotBlank(headerValue)) {\n // 验证token\n String token = headerValue.replace(WebConstants.TOKEN_VALUE_PREFIX, \"\");\n JWTObject jwtObject = JWTTokenBuilder.parseJWTToken(token, jwtProperties);\n if (jwtObject.isLegal()) {\n String uuid = jwtObject.getUuid();\n String storageToken = (String) this.ops.get(RedisConstants.USER_TOKEN_CACHE_PREFIX.concat(uuid));\n // 和服务端token比对,后期需要进行token的需求操作\n if (token.equals(storageToken)) {\n User user = (User) this.ops.get(RedisConstants.USER_TOKEN_PREFIX.concat(jwtObject.getUsername()));\n SecurityUser securityUser = new SecurityUser();\n securityUser.setUserDetail(user);\n UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());\n authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));\n SecurityContextHolder.getContext().setAuthentication(authenticationToken);\n }\n }\n }\n filterChain.doFilter(request, response);\n }\n\n\n}" }, { "identifier": "AccessDeniedHandlerImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/handler/AccessDeniedHandlerImpl.java", "snippet": "@Slf4j\npublic class AccessDeniedHandlerImpl implements AccessDeniedHandler {\n\n\n @Override\n public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {\n log.error(\"访问受限\", accessDeniedException);\n Result result = new Result(ResponseStatusEnum.ERROR)\n .add(\"detail\", \"访问受限制\");\n ServletUtils.reposeObjectWithJson(response, result);\n }\n\n\n}" }, { "identifier": "AuthenticationEntryPointImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/handler/AuthenticationEntryPointImpl.java", "snippet": "@Slf4j\npublic class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {\n\n\n /**\n * 认证失败的回调\n * TODO 相同的一段时间内同一账户认证失败次数达到5次之后就需要锁定账户,24小时之后恢复\n *\n * @param request 请求\n * @param response 响应\n * @param authException 异常信息\n * @throws IOException 异常信息\n * @throws ServletException 异常信息\n */\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {\n log.error(\"认证失败信息\", authException);\n String detailMessage = \"认证失败\";\n // TODO 待完善\n if (authException instanceof BadCredentialsException) {\n detailMessage = \"账号或者密码错误\";\n } else if (authException instanceof InsufficientAuthenticationException) {\n // 未提交用户登录名或者密码,或者验证码等信息才会抛出这个错误\n detailMessage = \"请检查登录参数是否齐全\";\n } else if (authException instanceof AccountStatusException) {\n // 账号状态异常\n detailMessage = \"账号已经被锁定,无法进行操作\";\n } else if (authException instanceof CaptchaNotValidException) {\n detailMessage = \"请检查验证码是否有误\";\n } else if (authException instanceof AuthenticationCredentialsNotFoundException) {\n detailMessage = \"无权限访问保护资源\";\n }\n addRequestToRestrictedAccessList(request);\n Result result = new Result(ResponseStatusEnum.ERROR).add(\"detail\", detailMessage);\n ServletUtils.reposeObjectWithJson(response, result);\n }\n\n\n /**\n * @param request 记录下客户端的错误请求信息,超出限制后服务端将会拒绝与客户端相同IP的所有请求\n */\n private void addRequestToRestrictedAccessList(HttpServletRequest request) {\n String clientIP = ServletUtils.getClientIP(request);\n if (!NetUtil.isInnerIP(clientIP)) {\n ClientInfo clientInfo = ServletUtils.getClientInfo(request);\n // TODO 记录异常信息和客户端信息\n log.info(\"记录下一次异常行为,客户端信息{}\", clientInfo);\n }\n }\n\n\n}" } ]
import cn.hubbo.common.domain.to.properties.JWTProperties; import cn.hubbo.security.filter.AccessDecisionManagerImpl; import cn.hubbo.security.filter.CustomFilterInvocationSecurityMetadataSource; import cn.hubbo.security.filter.DynamicFilter; import cn.hubbo.security.filter.FormAndJsonLoginFilter; import cn.hubbo.security.filter.JwtTokenFilter; import cn.hubbo.security.handler.AccessDeniedHandlerImpl; import cn.hubbo.security.handler.AuthenticationEntryPointImpl; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.filter.OncePerRequestFilter; import java.util.List;
4,727
package cn.hubbo.configuration.security; /** * @author 张晓华 * @version V1.0 * @Package cn.hubbo.configuration.security * @date 2023/10/20 23:51 * @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利 */ @Configuration @AllArgsConstructor public class SpringSecurityConfig { private UserDetailsService userDetailsService; private AuthenticationConfiguration authenticationConfiguration; private RedisTemplate<String, Object> redisTemplate; private JWTProperties jwtProperties; /** * @return 密码加密工具 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * @return 用户信息校验的工具 */ @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return daoAuthenticationProvider; } @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); httpSecurity.csrf(AbstractHttpConfigurer::disable) .sessionManagement(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)) .passwordManagement(AbstractHttpConfigurer::disable) .anonymous(AbstractHttpConfigurer::disable) .rememberMe(AbstractHttpConfigurer::disable) .headers(AbstractHttpConfigurer::disable) .authenticationManager(authenticationManager()) .httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{})) .permitAll() .anyRequest() .authenticated()) .authenticationProvider(authenticationProvider()) .exceptionHandling(web -> web .accessDeniedHandler(accessDeniedHandler()) .authenticationEntryPoint(authenticationEntryPoint())) //.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class) .addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } /** * @return 放行的资源 */ @Bean public WebSecurityCustomizer webSecurityCustomizer() { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{})); } @Bean public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) { FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties); loginFilter.setPostOnly(true); loginFilter.setFilterProcessesUrl("/user/login"); loginFilter.setAuthenticationManager(authenticationManager); loginFilter.setAllowSessionCreation(false); return loginFilter; } @Bean public AccessDeniedHandler accessDeniedHandler() { return new AccessDeniedHandlerImpl(); } @Bean public AuthenticationEntryPoint authenticationEntryPoint() {
package cn.hubbo.configuration.security; /** * @author 张晓华 * @version V1.0 * @Package cn.hubbo.configuration.security * @date 2023/10/20 23:51 * @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利 */ @Configuration @AllArgsConstructor public class SpringSecurityConfig { private UserDetailsService userDetailsService; private AuthenticationConfiguration authenticationConfiguration; private RedisTemplate<String, Object> redisTemplate; private JWTProperties jwtProperties; /** * @return 密码加密工具 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * @return 用户信息校验的工具 */ @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return daoAuthenticationProvider; } @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); httpSecurity.csrf(AbstractHttpConfigurer::disable) .sessionManagement(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)) .passwordManagement(AbstractHttpConfigurer::disable) .anonymous(AbstractHttpConfigurer::disable) .rememberMe(AbstractHttpConfigurer::disable) .headers(AbstractHttpConfigurer::disable) .authenticationManager(authenticationManager()) .httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{})) .permitAll() .anyRequest() .authenticated()) .authenticationProvider(authenticationProvider()) .exceptionHandling(web -> web .accessDeniedHandler(accessDeniedHandler()) .authenticationEntryPoint(authenticationEntryPoint())) //.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class) .addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } /** * @return 放行的资源 */ @Bean public WebSecurityCustomizer webSecurityCustomizer() { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{})); } @Bean public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) { FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties); loginFilter.setPostOnly(true); loginFilter.setFilterProcessesUrl("/user/login"); loginFilter.setAuthenticationManager(authenticationManager); loginFilter.setAllowSessionCreation(false); return loginFilter; } @Bean public AccessDeniedHandler accessDeniedHandler() { return new AccessDeniedHandlerImpl(); } @Bean public AuthenticationEntryPoint authenticationEntryPoint() {
return new AuthenticationEntryPointImpl();
7
2023-10-18 09:38:29+00:00
8k
RoessinghResearch/senseeact
ExampleSenSeeActService/src/main/java/nl/rrd/senseeact/exampleservice/ExampleApplicationInit.java
[ { "identifier": "MobileAppRepository", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/MobileAppRepository.java", "snippet": "@AppComponent\npublic abstract class MobileAppRepository {\n\tprotected abstract List<MobileApp> getMobileApps();\n\n\tpublic MobileApp forAndroidPackage(String pkg)\n\t\t\tthrows IllegalArgumentException {\n\t\tList<MobileApp> apps = getMobileApps();\n\t\tfor (MobileApp app : apps) {\n\t\t\tif (pkg.equals(app.getAndroidPackage()))\n\t\t\t\treturn app;\n\t\t}\n\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\"Mobile app with Android package %s not found\", pkg));\n\t}\n\n\tpublic MobileApp forCode(String code) throws IllegalArgumentException {\n\t\tList<MobileApp> apps = getMobileApps();\n\t\tfor (MobileApp app : apps) {\n\t\t\tif (code.equalsIgnoreCase(app.getCode()))\n\t\t\t\treturn app;\n\t\t}\n\t\tthrow new IllegalArgumentException(String.format(\n\t\t\t\t\"Mobile app with code \\\"%s\\\" not found\", code));\n\t}\n}" }, { "identifier": "ProjectRepository", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/project/ProjectRepository.java", "snippet": "@AppComponent\npublic abstract class ProjectRepository {\n\tprivate final Object lock = new Object();\n\tprivate List<BaseProject> projects = null;\n\n\t/**\n\t * Returns all projects. Note that a user may not be allowed to access\n\t * every project on the server. See also {@link\n\t * SenSeeActClient#getProjectList() getProjectList()}.\n\t * \n\t * @return the projects\n\t */\n\tpublic List<BaseProject> getProjects() {\n\t\tsynchronized (lock) {\n\t\t\tif (projects != null)\n\t\t\t\treturn projects;\n\t\t\tprojects = createProjects();\n\t\t\treturn projects;\n\t\t}\n\t}\n\n\tprotected abstract List<BaseProject> createProjects();\n\n\t/**\n\t * Finds the project with the specified code. If no such project exists,\n\t * this method returns null. Note that a user may not be allowed to access\n\t * the project on the server. See also {@link\n\t * SenSeeActClient#getProjectList() RRDSenSeeActClient.getProjectList()}.\n\t * \n\t * @param code the project code\n\t * @return the project or null\n\t */\n\tpublic BaseProject findProjectByCode(String code) {\n\t\tList<BaseProject> projects = getProjects();\n\t\tfor (BaseProject project : projects) {\n\t\t\tif (project.getCode().equals(code))\n\t\t\t\treturn project;\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "DatabaseFactory", "path": "DataAccessObjects/src/main/java/nl/rrd/senseeact/dao/DatabaseFactory.java", "snippet": "@AppComponent\npublic abstract class DatabaseFactory {\n\tprivate boolean syncEnabled = false;\n\tprivate boolean saveSyncedRemoteActions = true;\n\n\t/**\n\t * Returns whether action logging is enabled for synchronisation with\n\t * a remote database.\n\t *\n\t * @return true if synchronisation logging is enabled, false otherwise\n\t */\n\tpublic boolean isSyncEnabled() {\n\t\treturn syncEnabled;\n\t}\n\n\t/**\n\t * Returns whether action logging should be enabled for synchronisation\n\t * with a remote database.\n\t *\n\t * @param syncEnabled true if synchronisation logging is enabled, false\n\t * otherwise\n\t */\n\tpublic void setSyncEnabled(boolean syncEnabled) {\n\t\tthis.syncEnabled = syncEnabled;\n\t}\n\n\t/**\n\t * If synchronization logging is enabled (see {@link #isSyncEnabled()\n\t * isSyncEnabled()}), this method returns whether database actions received\n\t * from the remote database should be logged as well. If this is false,\n\t * then only local database actions are logged. The default is true.\n\t * \n\t * @return true if remote database actions are logged, false if only local\n\t * database actions are logged\n\t */\n\tpublic boolean isSaveSyncedRemoteActions() {\n\t\treturn saveSyncedRemoteActions;\n\t}\n\n\t/**\n\t * If synchronization logging is enabled (see {@link\n\t * #setSyncEnabled(boolean) setSyncEnabled()}), this method determines\n\t * whether database actions received from the remote database should be\n\t * logged as well. If this is false, then only local database actions are\n\t * logged. The default is true.\n\t * \n\t * @param saveSyncedRemoteActions true if remote database actions are\n\t * logged, false if only local database actions are logged\n\t */\n\tpublic void setSaveSyncedRemoteActions(boolean saveSyncedRemoteActions) {\n\t\tthis.saveSyncedRemoteActions = saveSyncedRemoteActions;\n\t}\n\n\t/**\n\t * Returns a new instance of {@link MemoryDatabaseFactory\n\t * MemoryDatabaseFactory}. This method is called as a default when you\n\t * get an instance from {@link AppComponents AppComponents} and you haven't\n\t * configured a specific subclass.\n\t * \n\t * @return a new memory database factory\n\t */\n\tpublic static DatabaseFactory getInstance() {\n\t\treturn new MemoryDatabaseFactory();\n\t}\n\n\t/**\n\t * Connects to the database server and returns a {@link DatabaseConnection\n\t * DatabaseConnection}. When you no longer need the connection, you should\n\t * call {@link DatabaseConnection#close() close()}.\n\t *\n\t * <p>The returned connection will be configured for action logging as you\n\t * have configured this factory.</p>\n\t *\n\t * @return the database connection\n\t * @throws IOException if the connection could not be established\n\t */\n\tpublic DatabaseConnection connect() throws IOException {\n\t\tDatabaseConnection conn = doConnect();\n\t\tconn.setSyncEnabled(syncEnabled);\n\t\tconn.setSaveSyncedRemoteActions(saveSyncedRemoteActions);\n\t\treturn conn;\n\t}\n\t\n\t/**\n\t * Connects to the database server and returns a {@link DatabaseConnection\n\t * DatabaseConnection}. When you no longer need the connection, you should\n\t * call {@link DatabaseConnection#close() close()}.\n\t * \n\t * @return the database connection\n\t * @throws IOException if the connection could not be established\n\t */\n\tprotected abstract DatabaseConnection doConnect() throws IOException;\n}" }, { "identifier": "ExampleMobileAppRepository", "path": "ExampleSenSeeActClient/src/main/java/nl/rrd/senseeact/exampleclient/ExampleMobileAppRepository.java", "snippet": "@AppComponent\npublic class ExampleMobileAppRepository extends MobileAppRepository {\n\t@Override\n\tprotected List<MobileApp> getMobileApps() {\n\t\tList<MobileApp> apps = new ArrayList<>();\n\t\tapps.add(new MobileApp(\n\t\t\t\t\"senseeact\",\n\t\t\t\t\"SenSeeAct\",\n\t\t\t\t\"nl.rrd.senseeact\"));\n\t\treturn apps;\n\t}\n}" }, { "identifier": "ExampleProjectRepository", "path": "ExampleSenSeeActClient/src/main/java/nl/rrd/senseeact/exampleclient/project/ExampleProjectRepository.java", "snippet": "public class ExampleProjectRepository extends ProjectRepository {\n\t@Override\n\tprotected List<BaseProject> createProjects() {\n\t\treturn List.of(\n\t\t\tnew DefaultProject()\n\t\t);\n\t}\n}" }, { "identifier": "ApplicationInit", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/ApplicationInit.java", "snippet": "public abstract class ApplicationInit {\n\tprivate final Object LOCK = new Object();\n\tprivate boolean dbInitStarted = false;\n\n\t/**\n\t * Constructs a new application. It reads service.properties and\n\t * initialises the {@link Configuration Configuration} and the {@link\n\t * AppComponents AppComponents} with the {@link DatabaseFactory\n\t * DatabaseFactory}.\n\t * \n\t * @throws Exception if the application can't be initialised\n\t */\n\tpublic ApplicationInit() throws Exception {\n\t\tAppComponents components = AppComponents.getInstance();\n\t\tClassLoader classLoader = ApplicationInit.class.getClassLoader();\n\t\tURL propsUrl = classLoader.getResource(\"service.properties\");\n\t\tif (propsUrl == null) {\n\t\t\tthrow new Exception(\"Can't find resource service.properties. \" +\n\t\t\t\t\t\"Did you run gradlew updateConfig?\");\n\t\t}\n\t\tConfiguration config = createConfiguration();\n\t\tconfig.loadProperties(propsUrl);\n\t\tpropsUrl = classLoader.getResource(\"deployment.properties\");\n\t\tconfig.loadProperties(propsUrl);\n\t\tif (components.findComponent(Configuration.class) == null)\n\t\t\tcomponents.addComponent(config);\n\t\tif (components.findComponent(DatabaseFactory.class) == null)\n\t\t\tcomponents.addComponent(createDatabaseFactory());\n\t\tif (components.findComponent(OAuthTableRepository.class) == null)\n\t\t\tcomponents.addComponent(createOAuthTableRepository());\n\t\tif (components.findComponent(SSOTokenRepository.class) == null)\n\t\t\tcomponents.addComponent(createSSOTokenRepository());\n\t\tif (components.findComponent(\n\t\t\t\tEmailTemplateRepository.class) == null) {\n\t\t\tcomponents.addComponent(createResetPasswordTemplateRepository());\n\t\t}\n\t\tif (components.findComponent(ProjectRepository.class) == null)\n\t\t\tcomponents.addComponent(createProjectRepository());\n\t\tif (components.findComponent(\n\t\t\t\tProjectUserAccessControlRepository.class) == null) {\n\t\t\tcomponents.addComponent(createProjectUserAccessControlRepository());\n\t\t}\n\t\tif (components.findComponent(MobileAppRepository.class) == null)\n\t\t\tcomponents.addComponent(createMobileAppRepository());\n\t\tif (components.findComponent(DataExporterFactory.class) == null)\n\t\t\tcomponents.addComponent(createDataExporterFactory());\n\t\tif (components.findComponent(TaskScheduler.class) == null)\n\t\t\tcomponents.addComponent(new DefaultTaskScheduler());\n\t\tfinal Logger logger = AppComponents.getLogger(SenSeeActContext.LOGTAG);\n\t\tThread.setDefaultUncaughtExceptionHandler((thread, ex) ->\n\t\t\tlogger.error(\"Uncaught exception: \" + ex.getMessage(), ex)\n\t\t);\n\t\tString dataDir = config.get(Configuration.DATA_DIR);\n\t\tSystem.setOut(StdOutLogger.createStdOut(dataDir));\n\t\tSystem.setErr(StdOutLogger.createStdErr(dataDir));\n\t\tlogger.info(\"SenSeeAct version: \" + config.get(Configuration.VERSION));\n\t\tPushNotificationService pushService = AppComponents.get(\n\t\t\t\tPushNotificationService.class);\n\t\tpushService.startService();\n\t\tnew Thread(() -> {\n\t\t\ttry {\n\t\t\t\tinitDatabases();\n\t\t\t} catch (Exception ex) {\n\t\t\t\tlogger.error(\"Can't initialize databases: \" +\n\t\t\t\t\t\tex.getMessage(), ex);\n\t\t\t}\n\t\t}).start();\n\t}\n\t\n\t/**\n\t * Initializes the authentication database and all project databases.\n\t * \n\t * @throws Exception if any error occurs\n\t */\n\tprivate void initDatabases() throws Exception {\n\t\tsynchronized (LOCK) {\n\t\t\tif (dbInitStarted)\n\t\t\t\treturn;\n\t\t\tdbInitStarted = true;\n\t\t}\n\t\tLogger logger = AppComponents.getLogger(SenSeeActContext.LOGTAG);\n\t\tlogger.info(\"Start initialization of databases\");\n\t\tDatabaseLoader dbLoader = DatabaseLoader.getInstance();\n\t\tDatabaseConnection dbConn = dbLoader.openConnection();\n\t\ttry {\n\t\t\tdbLoader.initAuthDatabase(dbConn);\n\t\t\tProjectRepository projectRepo = AppComponents.get(\n\t\t\t\t\tProjectRepository.class);\n\t\t\tList<BaseProject> projects = projectRepo.getProjects();\n\t\t\tfor (BaseProject project : projects) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t\t\"Start database initialization for project \" +\n\t\t\t\t\t\tproject.getCode());\n\t\t\t\tList<? extends DatabaseTableDef<?>> tables =\n\t\t\t\t\t\tproject.getDatabaseTables();\n\t\t\t\tif (tables != null && !tables.isEmpty()) {\n\t\t\t\t\tdbLoader.initProjectDatabase(dbConn, project.getCode());\n\t\t\t\t}\n\t\t\t\tlogger.info(\n\t\t\t\t\t\t\"Completed database initialization for project \" +\n\t\t\t\t\t\tproject.getCode());\n\t\t\t}\n\t\t} finally {\n\t\t\tdbConn.close();\n\t\t}\n\t\tlogger.info(\"Completed initialization of databases\");\n\t}\n\n\tprotected abstract Configuration createConfiguration();\n\n\t/**\n\t * Creates a DatabaseFactory using properties in the configuration.\n\t * \n\t * @return the DatabaseFactory\n\t * @throws ParseException if the configuration is invalid\n\t */\n\tprotected abstract DatabaseFactory createDatabaseFactory()\n\t\t\tthrows ParseException;\n\n\tprotected DatabaseFactory createMySQLDatabaseFactory()\n\t\t\tthrows ParseException {\n\t\tConfiguration config = AppComponents.get(Configuration.class);\n\t\tMySQLDatabaseFactory dbFactory = new MySQLDatabaseFactory();\n\t\tString host = config.get(Configuration.MYSQL_HOST);\n\t\tif (host != null)\n\t\t\tdbFactory.setHost(host);\n\t\tString portStr = config.get(Configuration.MYSQL_PORT);\n\t\tif (portStr != null) {\n\t\t\ttry {\n\t\t\t\tdbFactory.setPort(Integer.parseInt(portStr));\n\t\t\t} catch (NumberFormatException ex) {\n\t\t\t\tthrow new ParseException(\n\t\t\t\t\t\t\"Invalid value for property mysqlPort: \" + portStr);\n\t\t\t}\n\t\t}\n\t\tdbFactory.setUser(\"root\");\n\t\tdbFactory.setSyncEnabled(true);\n\t\tString password = config.get(Configuration.MYSQL_ROOT_PASSWORD);\n\t\tif (password == null)\n\t\t\tthrow new ParseException(\"Property mysqlRootPassword not found\");\n\t\tdbFactory.setPassword(password);\n\t\treturn dbFactory;\n\t}\n\n\tprotected abstract OAuthTableRepository createOAuthTableRepository();\n\n\tprotected abstract SSOTokenRepository createSSOTokenRepository();\n\n\tprotected abstract EmailTemplateRepository\n\tcreateResetPasswordTemplateRepository();\n\n\tprotected abstract ProjectRepository createProjectRepository();\n\n\tprotected abstract ProjectUserAccessControlRepository\n\tcreateProjectUserAccessControlRepository();\n\n\tprotected abstract MobileAppRepository createMobileAppRepository();\n\n\tprotected abstract DataExporterFactory createDataExporterFactory();\n\n\tpublic void onApplicationEvent(ContextClosedEvent event) {\n\t\tPushNotificationService pushService = AppComponents.get(\n\t\t\t\tPushNotificationService.class);\n\t\tpushService.stopService();\n\t\tDatabaseLoader.getInstance().close();\n\t\tLogger logger = AppComponents.getLogger(SenSeeActContext.LOGTAG);\n\t\tlogger.info(\"Shutdown SenSeeAct\");\n\t}\n}" }, { "identifier": "Configuration", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/Configuration.java", "snippet": "@AppComponent\npublic class Configuration extends BaseConfiguration {\n\tpublic static final String MYSQL_HOST = \"mysqlHost\";\n\tpublic static final String MYSQL_PORT = \"mysqlPort\";\n\tpublic static final String MYSQL_ROOT_PASSWORD = \"mysqlRootPassword\";\n\n\tpublic static final String DB_NAME_PREFIX = \"dbNamePrefix\";\n\tpublic static final String JWT_SECRET_KEY = \"jwtSecretKey\";\n\tpublic static final String SECRET_SALT = \"secretSalt\";\n\t\n\tpublic static final String ADMIN_EMAIL = \"adminEmail\";\n\tpublic static final String ADMIN_PASSWORD = \"adminPassword\";\n\t\n\tpublic static final String MAIL_HOST = \"mailHost\";\n\tpublic static final String MAIL_USERNAME = \"mailUsername\";\n\tpublic static final String MAIL_PASSWORD = \"mailPassword\";\n\tpublic static final String MAIL_SMTP_TLS = \"mailSmtpTls\";\n\tpublic static final String MAIL_FROM = \"mailFrom\";\n\t\n\tpublic static final String WEB_URL = \"webUrl\";\n\n\tpublic EmailConfiguration toEmailConfig() {\n\t\treturn EmailConfiguration.parse(\n\t\t\t\tget(MAIL_HOST),\n\t\t\t\tget(MAIL_USERNAME),\n\t\t\t\tget(MAIL_PASSWORD),\n\t\t\t\tget(MAIL_SMTP_TLS),\n\t\t\t\tget(MAIL_FROM)\n\t\t);\n\t}\n}" }, { "identifier": "OAuthTableRepository", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/OAuthTableRepository.java", "snippet": "@AppComponent\npublic abstract class OAuthTableRepository {\n\tpublic abstract List<DatabaseTableDef<?>> getOAuthTables();\n}" }, { "identifier": "DataExporterFactory", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/export/DataExporterFactory.java", "snippet": "@AppComponent\npublic interface DataExporterFactory {\n\tList<String> getProjectCodes();\n\tDataExporter create(String project, String id, User user,\n\t\t\tSenSeeActClient client, File dir, DataExportListener listener);\n}" }, { "identifier": "EmailTemplateRepository", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/mail/EmailTemplateRepository.java", "snippet": "@AppComponent\npublic interface EmailTemplateRepository {\n\t/**\n\t * Returns the template collection for a reset password email. The templates\n\t * take the following parameters for the HTML content:\n\t *\n\t * <p><ul>\n\t * <li>code: the reset code</li>\n\t * </ul></p>\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getResetPasswordTemplates();\n\n\t/**\n\t * Returns the template collection for a new user email, where the user\n\t * is asked to confirm their email address. The templates take the following\n\t * parameters for the HTML content:\n\t *\n\t * <p><ul>\n\t * <li>code: the confirmation code</li>\n\t * </ul></p>\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getNewUserTemplates();\n\n\t/**\n\t * Returns the template collection for email that is sent when a user\n\t * changes their email address. This mail is sent to the old address if that\n\t * address was verified, and it will mention the new address. The templates\n\t * take the following parameters for the HTML content:\n\t *\n\t * <p><ul>\n\t * <li>new_email: the new email address</li>\n\t * </ul></p>\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getEmailChangedOldVerifiedTemplates();\n\n\t/**\n\t * Returns the template collection for email that is sent when a user\n\t * changes their email address. This mail is sent to the old address if that\n\t * address was not verified. Because the old address was not verified, the\n\t * new address will not be mentioned. The templates do not need parameters\n\t * for the HTML content.\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getEmailChangedOldUnverifiedTemplates();\n\n\t/**\n\t * Returns the template collection for email that is sent when a user\n\t * changes their email address, while the old address was verified. This\n\t * mail is sent to the new address. The user is asked to confirm the new\n\t * address. The templates take the following parameters for the HTML\n\t * content:\n\t *\n\t * <p><ul>\n\t * <li>old_email: the old email address</li>\n\t * <li>new_email: the new email address</li>\n\t * <li>code: the confirmation code</li>\n\t * </ul></p>\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getEmailChangedNewVerifiedTemplates();\n\n\t/**\n\t * Returns the template collection for email that is sent when a user\n\t * changes their email address, while the old address was not verified. This\n\t * mail is sent to the new address. The user is asked to confirm the new\n\t * address. The templates take the following parameters for the HTML\n\t * content:\n\t *\n\t * <p><ul>\n\t * <li>old_email: the old email address</li>\n\t * <li>new_email: the new email address</li>\n\t * <li>code: the confirmation code</li>\n\t * </ul></p>\n\t *\n\t * @return the template collection\n\t */\n\tEmailTemplateCollection getEmailChangedNewUnverifiedTemplates();\n}" }, { "identifier": "SSOTokenRepository", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/sso/SSOTokenRepository.java", "snippet": "@AppComponent\npublic abstract class SSOTokenRepository {\n\tpublic abstract List<SSOToken> getTokens();\n}" } ]
import nl.rrd.senseeact.client.MobileAppRepository; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.DatabaseFactory; import nl.rrd.senseeact.exampleclient.ExampleMobileAppRepository; import nl.rrd.senseeact.exampleclient.project.ExampleProjectRepository; import nl.rrd.senseeact.service.ApplicationInit; import nl.rrd.senseeact.service.Configuration; import nl.rrd.senseeact.service.OAuthTableRepository; import nl.rrd.senseeact.service.ProjectUserAccessControlRepository; import nl.rrd.senseeact.service.export.DataExporterFactory; import nl.rrd.senseeact.service.mail.EmailTemplateRepository; import nl.rrd.senseeact.service.sso.SSOTokenRepository; import nl.rrd.utils.exception.ParseException;
4,848
package nl.rrd.senseeact.exampleservice; public class ExampleApplicationInit extends ApplicationInit { public ExampleApplicationInit() throws Exception { } @Override protected Configuration createConfiguration() { return ExampleConfiguration.getInstance(); } @Override protected DatabaseFactory createDatabaseFactory() throws ParseException { return createMySQLDatabaseFactory(); } @Override protected OAuthTableRepository createOAuthTableRepository() { return new ExampleOauthTableRepository(); } @Override protected SSOTokenRepository createSSOTokenRepository() { return new ExampleSSOTokenRepository(); } @Override protected EmailTemplateRepository createResetPasswordTemplateRepository() { return new ExampleEmailTemplateRepository(); } @Override protected ProjectRepository createProjectRepository() {
package nl.rrd.senseeact.exampleservice; public class ExampleApplicationInit extends ApplicationInit { public ExampleApplicationInit() throws Exception { } @Override protected Configuration createConfiguration() { return ExampleConfiguration.getInstance(); } @Override protected DatabaseFactory createDatabaseFactory() throws ParseException { return createMySQLDatabaseFactory(); } @Override protected OAuthTableRepository createOAuthTableRepository() { return new ExampleOauthTableRepository(); } @Override protected SSOTokenRepository createSSOTokenRepository() { return new ExampleSSOTokenRepository(); } @Override protected EmailTemplateRepository createResetPasswordTemplateRepository() { return new ExampleEmailTemplateRepository(); } @Override protected ProjectRepository createProjectRepository() {
return new ExampleProjectRepository();
4
2023-10-24 09:36:50+00:00
8k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/swerve/configs/NOTEBLOCK2023.java
[ { "identifier": "DefaultConfig", "path": "src/main/java/frc/spectrumLib/swerve/config/DefaultConfig.java", "snippet": "public class DefaultConfig {\n\n // Angle Offsets\n private static final double kFrontLeftCANcoderOffset = 0;\n private static final double kFrontRightCANncoderOffset = 0;\n private static final double kBackLeftCANcoderOffset = 0;\n private static final double kBackRightCANcoderOffset = 0;\n\n // Tuning Config\n // Estimated at first, then fudge-factored to make odom match record\n private static final double kWheelRadiusInches = 2;\n private static final double speedAt12VoltsMps = 6; // Units.feetToMeters(16);\n private static final double slipCurrent = 800;\n private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0);\n private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0);\n\n /*Rotation Controller*/\n private static final double kPRotationController = 0.0;\n private static final double kIRotationController = 0.0;\n private static final double kDRotationController = 0.0;\n\n // Device Setup\n private static final String kCANbusName = \"3847\";\n private static final boolean supportsPro = false;\n private static final SwerveModuleSteerFeedbackType steerFeedbackType =\n SwerveModuleSteerFeedbackType.RemoteCANcoder;\n\n private static final int kPigeonId = 0;\n private static final int kFrontLeftDriveMotorId = 1;\n private static final int kFrontLeftSteerMotorId = 2;\n private static final int kFrontLeftEncoderId = 3;\n private static final int kFrontRightDriveMotorId = 11;\n private static final int kFrontRightSteerMotorId = 12;\n private static final int kFrontRightEncoderId = 13;\n private static final int kBackLeftDriveMotorId = 21;\n private static final int kBackLeftSteerMotorId = 22;\n private static final int kBackLeftEncoderId = 23;\n private static final int kBackRightDriveMotorId = 31;\n private static final int kBackRightSteerMotorId = 32;\n private static final int kBackRightEncoderId = 33;\n\n // Physical Config\n private static final double wheelBaseInches = 21.5;\n private static final double trackWidthInches = 18.5;\n private static final double kDriveGearRatio =\n 6.746; // (50 / 14) * (17 / 27) * (45 / 15); // SDS L2\n private static final double kSteerGearRatio = 21.428; // (50.0 / 14.0) * (60.0 / 10.0); // SDS\n private static final boolean kSteerMotorReversed = true;\n private static final boolean kInvertLeftSide = false;\n private static final boolean kInvertRightSide = true;\n private static final double kCouplingGearRatio = 0; // SDS MK4\n\n // Simulation Config\n private static double kSteerInertia = 0.00001;\n private static double kDriveInertia = 0.001;\n\n // Wheel Positions\n private static final double kFrontLeftXPosInches = wheelBaseInches / 2.0;\n private static final double kFrontLeftYPosInches = trackWidthInches / 2.0;\n private static final double kFrontRightXPosInches = wheelBaseInches / 2.0;\n private static final double kFrontRightYPosInches = -trackWidthInches / 2.0;\n private static final double kBackLeftXPosInches = -wheelBaseInches / 2.0;\n private static final double kBackLeftYPosInches = trackWidthInches / 2.0;\n private static final double kBackRightXPosInches = -wheelBaseInches / 2.0;\n private static final double kBackRightYPosInches = -trackWidthInches / 2.0;\n\n public static class SlotGains extends Slot0Configs {\n public SlotGains(double kP, double kI, double kD, double kV, double kS) {\n this.kP = kP;\n this.kI = kI;\n this.kD = kD;\n this.kV = kV;\n this.kS = kS;\n }\n }\n\n public static final ModuleConfigFactory ModuleCreator =\n new ModuleConfigFactory()\n .withDriveMotorGearRatio(kDriveGearRatio)\n .withSteerMotorGearRatio(kSteerGearRatio)\n .withCouplingGearRatio(kCouplingGearRatio)\n .withWheelRadius(kWheelRadiusInches)\n .withSlipCurrent(slipCurrent)\n .withSteerMotorGains(steerGains)\n .withDriveMotorGains(driveGains)\n .withSpeedAt12VoltsMps(speedAt12VoltsMps)\n .withSteerInertia(kSteerInertia)\n .withDriveInertia(kDriveInertia)\n .withFeedbackSource(steerFeedbackType)\n .withSteerMotorInverted(kSteerMotorReversed);\n\n public static final ModuleConfig FrontLeft =\n ModuleCreator.createModuleConfig(\n kFrontLeftSteerMotorId,\n kFrontLeftDriveMotorId,\n kFrontLeftEncoderId,\n kFrontLeftCANcoderOffset,\n Units.inchesToMeters(kFrontLeftXPosInches),\n Units.inchesToMeters(kFrontLeftYPosInches),\n kInvertLeftSide);\n\n public static final ModuleConfig FrontRight =\n ModuleCreator.createModuleConfig(\n kFrontRightSteerMotorId,\n kFrontRightDriveMotorId,\n kFrontRightEncoderId,\n kFrontRightCANncoderOffset,\n Units.inchesToMeters(kFrontRightXPosInches),\n Units.inchesToMeters(kFrontRightYPosInches),\n kInvertRightSide);\n\n public static final ModuleConfig BackLeft =\n ModuleCreator.createModuleConfig(\n kBackLeftSteerMotorId,\n kBackLeftDriveMotorId,\n kBackLeftEncoderId,\n kBackLeftCANcoderOffset,\n Units.inchesToMeters(kBackLeftXPosInches),\n Units.inchesToMeters(kBackLeftYPosInches),\n kInvertLeftSide);\n\n public static final ModuleConfig BackRight =\n ModuleCreator.createModuleConfig(\n kBackRightSteerMotorId,\n kBackRightDriveMotorId,\n kBackRightEncoderId,\n kBackRightCANcoderOffset,\n Units.inchesToMeters(kBackRightXPosInches),\n Units.inchesToMeters(kBackRightYPosInches),\n kInvertRightSide);\n\n public static final ModuleConfig[] ModuleConfigs = {FrontLeft, FrontRight, BackLeft, BackRight};\n\n public static final SwerveConfig DrivetrainConstants =\n new SwerveConfig()\n .withPigeon2Id(kPigeonId)\n .withCANbusName(kCANbusName)\n .withSupportsPro(supportsPro)\n .withModules(ModuleConfigs)\n .withRotationGains(\n kPRotationController, kIRotationController, kDRotationController);\n}" }, { "identifier": "SlotGains", "path": "src/main/java/frc/spectrumLib/swerve/config/DefaultConfig.java", "snippet": "public static class SlotGains extends Slot0Configs {\n public SlotGains(double kP, double kI, double kD, double kV, double kS) {\n this.kP = kP;\n this.kI = kI;\n this.kD = kD;\n this.kV = kV;\n this.kS = kS;\n }\n}" }, { "identifier": "ModuleConfig", "path": "src/main/java/frc/spectrumLib/swerve/config/ModuleConfig.java", "snippet": "public class ModuleConfig {\n public enum SwerveModuleSteerFeedbackType {\n RemoteCANcoder,\n FusedCANcoder,\n SyncCANcoder,\n }\n\n /** CAN ID of the drive motor */\n public int DriveMotorId = 0;\n /** CAN ID of the steer motor */\n public int SteerMotorId = 0;\n /** CAN ID of the CANcoder used for azimuth or RIO AnalogInput ID of the Analog Sensor used */\n public int AngleEncoderId = 0;\n /** Offset of the CANcoder in degrees */\n public double CANcoderOffset = 0;\n /** Gear ratio between drive motor and wheel */\n public double DriveMotorGearRatio = 0;\n /** Gear ratio between steer motor and CANcoder An example ratio for the SDS Mk4: 12.8 */\n public double SteerMotorGearRatio = 0;\n /** Coupled gear ratio between the CANcoder and the drive motor */\n public double CouplingGearRatio = 0;\n /** Wheel radius of the driving wheel in inches */\n public double WheelRadius = 0;\n /**\n * The location of this module's wheels relative to the physical center of the robot in meters\n * along the X axis of the robot\n */\n public double LocationX = 0;\n /**\n * The location of this module's wheels relative to the physical center of the robot in meters\n * along the Y axis of the robot\n */\n public double LocationY = 0;\n\n /** The steer motor gains */\n public Slot0Configs SteerMotorGains = new Slot0Configs();\n /** The drive motor gains */\n public Slot0Configs DriveMotorGains = new Slot0Configs();\n\n /** The maximum amount of current the drive motors can apply without slippage */\n public double SlipCurrent = 400;\n\n /** True if the steering motor is reversed from the CANcoder */\n public boolean SteerMotorInverted = false;\n /** True if the driving motor is reversed */\n public boolean DriveMotorInverted = false;\n\n /** Sim-specific constants * */\n /** Azimuthal inertia in kilogram meters squared */\n public double SteerInertia = 0.001;\n /** Drive inertia in kilogram meters squared */\n public double DriveInertia = 0.001;\n\n /**\n * When using open-loop drive control, this specifies the speed the robot travels at when driven\n * with 12 volts in meters per second. This is used to approximate the output for a desired\n * velocity. If using closed loop control, this value is ignored\n */\n public double SpeedAt12VoltsMps = 0;\n\n /**\n * Choose how the feedback sensors should be configured\n *\n * <p>If the robot does not support Pro, then this should remain as RemoteCANcoder. Otherwise,\n * users have the option to use either FusedCANcoder or SyncCANcoder depending on if there is\n * risk that the CANcoder can fail in a way to provide \"good\" data.\n */\n public SwerveModuleSteerFeedbackType FeedbackSource =\n SwerveModuleSteerFeedbackType.RemoteCANcoder;\n\n public double MotionMagicAcceleration = 100.0;\n public double MotionMagicCruiseVelocity = 10;\n\n public ModuleConfig withDriveMotorId(int id) {\n this.DriveMotorId = id;\n return this;\n }\n\n public ModuleConfig withSteerMotorId(int id) {\n this.SteerMotorId = id;\n return this;\n }\n\n public ModuleConfig withCANcoderId(int id) {\n this.AngleEncoderId = id;\n return this;\n }\n\n public ModuleConfig withCANcoderOffset(double offset) {\n this.CANcoderOffset = offset;\n return this;\n }\n\n public ModuleConfig withDriveMotorGearRatio(double ratio) {\n this.DriveMotorGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withSteerMotorGearRatio(double ratio) {\n this.SteerMotorGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withCouplingGearRatio(double ratio) {\n this.CouplingGearRatio = ratio;\n return this;\n }\n\n public ModuleConfig withWheelRadius(double radius) {\n this.WheelRadius = radius;\n return this;\n }\n\n public ModuleConfig withLocationX(double locationXMeters) {\n this.LocationX = locationXMeters;\n return this;\n }\n\n public ModuleConfig withLocationY(double locationYMeters) {\n this.LocationY = locationYMeters;\n return this;\n }\n\n public ModuleConfig withSteerMotorGains(Slot0Configs gains) {\n this.SteerMotorGains = gains;\n return this;\n }\n\n public ModuleConfig withDriveMotorGains(Slot0Configs gains) {\n this.DriveMotorGains = gains;\n return this;\n }\n\n public ModuleConfig withSlipCurrent(double slipCurrent) {\n this.SlipCurrent = slipCurrent;\n return this;\n }\n\n public ModuleConfig withSteerMotorInverted(boolean SteerMotorInverted) {\n this.SteerMotorInverted = SteerMotorInverted;\n return this;\n }\n\n public ModuleConfig withDriveMotorInverted(boolean DriveMotorInverted) {\n this.DriveMotorInverted = DriveMotorInverted;\n return this;\n }\n\n public ModuleConfig withSpeedAt12VoltsMps(double speedAt12VoltsMps) {\n this.SpeedAt12VoltsMps = speedAt12VoltsMps;\n return this;\n }\n\n public ModuleConfig withSimulationSteerInertia(double steerInertia) {\n this.SteerInertia = steerInertia;\n return this;\n }\n\n public ModuleConfig withSimulationDriveInertia(double driveInertia) {\n this.DriveInertia = driveInertia;\n return this;\n }\n\n public ModuleConfig withFeedbackSource(SwerveModuleSteerFeedbackType source) {\n this.FeedbackSource = source;\n return this;\n }\n\n public ModuleConfig withMotionMagicAcceleration(double acceleration) {\n this.MotionMagicAcceleration = acceleration;\n return this;\n }\n\n public ModuleConfig withMotionMagicCruiseVelocity(double cruiseVelocity) {\n this.MotionMagicCruiseVelocity = cruiseVelocity;\n return this;\n }\n}" }, { "identifier": "SwerveModuleSteerFeedbackType", "path": "src/main/java/frc/spectrumLib/swerve/config/ModuleConfig.java", "snippet": "public enum SwerveModuleSteerFeedbackType {\n RemoteCANcoder,\n FusedCANcoder,\n SyncCANcoder,\n}" }, { "identifier": "SwerveConfig", "path": "src/main/java/frc/spectrumLib/swerve/config/SwerveConfig.java", "snippet": "public class SwerveConfig {\n /** CAN ID of the Pigeon2 on the drivetrain */\n public int Pigeon2Id = 0;\n /** Name of CANivore the swerve drive is on */\n public String CANbusName = \"rio\";\n\n /** If using Pro, specify this as true to make use of all the Pro features */\n public boolean SupportsPro = false;\n\n public ModuleConfig[] modules = new ModuleConfig[0];\n\n /*Rotation Controller*/\n public double kPRotationController = 0.0;\n public double kIRotationController = 0.0;\n public double kDRotationController = 0.0;\n\n /*Profiling Configs*/\n public double maxVelocity = 0;\n public double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.\n public double maxAngularVelocity = Math.PI * 2;\n public double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);\n\n public SwerveConfig withPigeon2Id(int id) {\n this.Pigeon2Id = id;\n return this;\n }\n\n public SwerveConfig withCANbusName(String name) {\n this.CANbusName = name;\n return this;\n }\n\n public SwerveConfig withSupportsPro(boolean supportsPro) {\n this.SupportsPro = supportsPro;\n return this;\n }\n\n public SwerveConfig withModules(ModuleConfig[] modules) {\n this.modules = modules;\n return this;\n }\n\n public SwerveConfig withRotationGains(double kP, double kI, double kD) {\n this.kPRotationController = kP;\n this.kIRotationController = kI;\n this.kDRotationController = kD;\n return this;\n }\n\n public SwerveConfig withProfilingConfigs(\n double maxVelocity,\n double maxAccel,\n double maxAngularVelocity,\n double maxAngularAcceleration) {\n this.maxVelocity = maxVelocity;\n this.maxAccel = maxAccel;\n this.maxAngularVelocity = maxAngularVelocity;\n this.maxAngularAcceleration = maxAngularAcceleration;\n return this;\n }\n}" } ]
import edu.wpi.first.math.util.Units; import frc.spectrumLib.swerve.config.DefaultConfig; import frc.spectrumLib.swerve.config.DefaultConfig.SlotGains; import frc.spectrumLib.swerve.config.ModuleConfig; import frc.spectrumLib.swerve.config.ModuleConfig.SwerveModuleSteerFeedbackType; import frc.spectrumLib.swerve.config.SwerveConfig;
4,932
package frc.robot.swerve.configs; public class NOTEBLOCK2023 { // Angle Offsets private static final double kFrontLeftCANcoderOffset = -0.407958984375; private static final double kFrontRightCANncoderOffset = -0.181396484375; private static final double kBackLeftCANcoderOffset = -0.8779296875; private static final double kBackRightCANcoderOffset = -0.84130859375; // Physical Config private static final double wheelBaseInches = 21.5; private static final double trackWidthInches = 18.5; private static final double kDriveGearRatio = 6.746; private static final double kSteerGearRatio = 21.428; // Tuning Config // Estimated at first, then fudge-factored to make odom match record private static final double kWheelRadiusInches = 2; private static final double speedAt12VoltsMps = 6; private static final double slipCurrent = 800; private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0); private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0); /*Rotation Controller*/ private static final double kPRotationController = 0.0; private static final double kIRotationController = 0.0; private static final double kDRotationController = 0.0; /*Profiling Configs*/ private static final double maxVelocity = speedAt12VoltsMps; private static final double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed. private static final double maxAngularVelocity = maxVelocity / Units.inchesToMeters( Math.hypot(wheelBaseInches / 2.0, trackWidthInches / 2.0)); private static final double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2); // Device Setup private static final String kCANbusName = "3847"; private static final boolean supportsPro = true; private static final SwerveModuleSteerFeedbackType steerFeedbackType = SwerveModuleSteerFeedbackType.FusedCANcoder; // Wheel Positions private static final double kFrontLeftXPos = Units.inchesToMeters(wheelBaseInches / 2.0); private static final double kFrontLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0); private static final double kFrontRightXPos = Units.inchesToMeters(wheelBaseInches / 2.0); private static final double kFrontRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0); private static final double kBackLeftXPos = Units.inchesToMeters(-wheelBaseInches / 2.0); private static final double kBackLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0); private static final double kBackRightXPos = Units.inchesToMeters(-wheelBaseInches / 2.0); private static final double kBackRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
package frc.robot.swerve.configs; public class NOTEBLOCK2023 { // Angle Offsets private static final double kFrontLeftCANcoderOffset = -0.407958984375; private static final double kFrontRightCANncoderOffset = -0.181396484375; private static final double kBackLeftCANcoderOffset = -0.8779296875; private static final double kBackRightCANcoderOffset = -0.84130859375; // Physical Config private static final double wheelBaseInches = 21.5; private static final double trackWidthInches = 18.5; private static final double kDriveGearRatio = 6.746; private static final double kSteerGearRatio = 21.428; // Tuning Config // Estimated at first, then fudge-factored to make odom match record private static final double kWheelRadiusInches = 2; private static final double speedAt12VoltsMps = 6; private static final double slipCurrent = 800; private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0); private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0); /*Rotation Controller*/ private static final double kPRotationController = 0.0; private static final double kIRotationController = 0.0; private static final double kDRotationController = 0.0; /*Profiling Configs*/ private static final double maxVelocity = speedAt12VoltsMps; private static final double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed. private static final double maxAngularVelocity = maxVelocity / Units.inchesToMeters( Math.hypot(wheelBaseInches / 2.0, trackWidthInches / 2.0)); private static final double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2); // Device Setup private static final String kCANbusName = "3847"; private static final boolean supportsPro = true; private static final SwerveModuleSteerFeedbackType steerFeedbackType = SwerveModuleSteerFeedbackType.FusedCANcoder; // Wheel Positions private static final double kFrontLeftXPos = Units.inchesToMeters(wheelBaseInches / 2.0); private static final double kFrontLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0); private static final double kFrontRightXPos = Units.inchesToMeters(wheelBaseInches / 2.0); private static final double kFrontRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0); private static final double kBackLeftXPos = Units.inchesToMeters(-wheelBaseInches / 2.0); private static final double kBackLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0); private static final double kBackRightXPos = Units.inchesToMeters(-wheelBaseInches / 2.0); private static final double kBackRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);
public static final ModuleConfig FrontLeft =
2
2023-10-23 17:01:53+00:00
8k
imart302/DulceNectar-BE
src/main/java/com/dulcenectar/java/services/ReviewServiceImpl.java
[ { "identifier": "CreateReviewDto", "path": "src/main/java/com/dulcenectar/java/dtos/review/CreateReviewDto.java", "snippet": "public class CreateReviewDto implements RequestDto<Review>{\n\t\n\tString review;\n\tInteger rating;\n\tInteger productId;\n\t\n\tpublic CreateReviewDto(String review, Integer rating, Integer productId) {\n\t\tsuper();\n\t\tthis.review = review;\n\t\tthis.rating = rating;\n\t\tthis.productId = productId;\n\t}\n\n\tpublic CreateReviewDto() {\n\t\tsuper();\n\t}\n\n\tpublic String getReview() {\n\t\treturn review;\n\t}\n\n\tpublic void setReview(String review) {\n\t\tthis.review = review;\n\t}\n\n\tpublic Integer getRating() {\n\t\treturn rating;\n\t}\n\n\tpublic void setRating(Integer rating) {\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Integer getProductId() {\n\t\treturn productId;\n\t}\n\n\tpublic void setProductId(Integer productId) {\n\t\tthis.productId = productId;\n\t}\n\n\t@Override\n\tpublic Review toEntity() {\n\t\tReview review1 = new Review();\n\t\treview1.setReview(review);\n\t\treview1.setRating(rating);\n\t\t\n\t\treturn review1;\n\t}\n\t\n\t\n\t\n\t\n\t\n}" }, { "identifier": "ResponseReviewDto", "path": "src/main/java/com/dulcenectar/java/dtos/review/ResponseReviewDto.java", "snippet": "public class ResponseReviewDto implements ResponseDto<Review> {\n\tprivate Integer id;\n\tprivate String userName;\n\tprivate String review;\n\tprivate Integer rating;\n\tprivate String productName;\n\tprivate String imgUrl;\n\t\n\tpublic ResponseReviewDto(Integer id, String userName, String review, Integer rating, String productName,\n\t\t\tString imgUrl) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.userName = userName;\n\t\tthis.review = review;\n\t\tthis.rating = rating;\n\t\tthis.productName = productName;\n\t\tthis.imgUrl = imgUrl;\n\t}\n\t\n\t\n\t\n\tpublic ResponseReviewDto(Integer id) {\n\t\tsuper();\n\t\tthis.id = id;\n\t}\n\n\tpublic ResponseReviewDto() {\n\t\tsuper();\n\t}\n\n\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\n\n\tpublic String getReview() {\n\t\treturn review;\n\t}\n\n\n\n\tpublic void setReview(String review) {\n\t\tthis.review = review;\n\t}\n\n\n\n\tpublic Integer getRating() {\n\t\treturn rating;\n\t}\n\n\n\n\tpublic void setRating(Integer rating) {\n\t\tthis.rating = rating;\n\t}\n\n\n\n\tpublic String getProductName() {\n\t\treturn productName;\n\t}\n\n\n\n\tpublic void setProductName(String productName) {\n\t\tthis.productName = productName;\n\t}\n\n\n\n\tpublic String getImgUrl() {\n\t\treturn imgUrl;\n\t}\n\n\n\n\tpublic void setImgUrl(String imgUrl) {\n\t\tthis.imgUrl = imgUrl;\n\t}\n\n\n\n\t@Override\n\tpublic ResponseReviewDto fromEntity(Review entity) {\n\t\tid = entity.getId();\n\t\tuserName = entity.getUser().getFirstName() + \" \" + entity.getUser().getLastName();\n\t\treview = entity.getReview();\n\t\trating = entity.getRating();\n\t\tproductName = entity.getProduct().getName();\n\t\timgUrl = entity.getProduct().getImgUrl();\n\t\t\n\t\treturn this;\n\t}\n}" }, { "identifier": "UpdateReviewDto", "path": "src/main/java/com/dulcenectar/java/dtos/review/UpdateReviewDto.java", "snippet": "public class UpdateReviewDto implements RequestDto<Review> {\n\n\tString review;\n\tInteger rating;\n\tInteger productId;\n\t\n\tpublic UpdateReviewDto( String review, Integer rating, Integer productId) {\n\t\tsuper();\n\t\tthis.review = review;\n\t\tthis.rating = rating;\n\t\tthis.productId = productId;\n\t}\n\n\tpublic UpdateReviewDto() {\n\t\tsuper();\n\t}\n\n\tpublic String getReview() {\n\t\treturn review;\n\t}\n\n\tpublic void setReview(String review) {\n\t\tthis.review = review;\n\t}\n\n\tpublic Integer getRating() {\n\t\treturn rating;\n\t}\n\n\tpublic void setRating(Integer rating) {\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Integer getProductId() {\n\t\treturn productId;\n\t}\n\n\tpublic void setProductId(Integer productId) {\n\t\tthis.productId = productId;\n\t}\n\n\t@Override\n\tpublic Review toEntity() {\n\t\tReview review1 = new Review();\n\t\treview1.setRating(rating);\n\t\treview1.setReview(review);\n\n\t\treturn review1;\n\t}\n\t\n\t\n}" }, { "identifier": "ProductNotFoundException", "path": "src/main/java/com/dulcenectar/java/exceptions/ProductNotFoundException.java", "snippet": "public class ProductNotFoundException extends RuntimeException {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic ProductNotFoundException() {\n\t\tsuper (\"El producto no existe\");\n\t}\n\n}" }, { "identifier": "ReviewNotFoundException", "path": "src/main/java/com/dulcenectar/java/exceptions/ReviewNotFoundException.java", "snippet": "public class ReviewNotFoundException extends RuntimeException {\n\t\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic ReviewNotFoundException() {\n\t\tsuper(\"No se ha encontrado la reseña\");\n\t}\n}" }, { "identifier": "Product", "path": "src/main/java/com/dulcenectar/java/models/Product.java", "snippet": "@Entity\n@Table(name=\"products\")\npublic class Product {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\tprivate String name;\n\tprivate String info;\n\n\tprivate Float gram;\n\tprivate String imgUrl;\n\tprivate Double price;\n\tprivate Long stock;\n\tprivate String typeGram;\n\t@CreationTimestamp\n\tprivate LocalDateTime createdAt;\n\t@UpdateTimestamp\n\tprivate LocalDateTime updatedAt;\n\n\t\n\t@ManyToOne\n\t@JoinColumn(name=\"category_id\", nullable=false)\n\tprivate Category category;\n/*\n * Quiza este no se necesie, como mencionaan en la clase, Oder no tiene relacion fundamental con las ordenes, mas que nada User es el que usa las orderPoducts\n * @OneToMany(mappedBy = \"Product\")\n * Private Set<OrderProducts> orderProduct;\n * \n */\n\n/*\n * Aqui, EN el conolador de reviews ya hay un et rEviews, se necesiaia aqui?`\n * El frontEnd no usa ninguna paina que muestre los reviews de un producto, pero tiene una seccion con todas las reviews\n * En esa seccion se haía un filtro\n * @OneToMany(mappedBy = \"Product\")\n * Private Set<Review> = reviewsList;\n * \n */\n\n\n\t\n\n\n\tpublic Product(Integer id, String name, String info, Float gram, String imgUrl, Double price,\n\t\t\tLong stock, String typeGram, LocalDateTime createdAt, LocalDateTime updatedAt, Category category) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.info = info;\n\t\tthis.gram = gram;\n\t\tthis.imgUrl = imgUrl;\n\t\tthis.price = price;\n\t\tthis.stock = stock;\n\t\tthis.typeGram = typeGram;\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t\tthis.category = category;\n\t}\n\t\n\tpublic Product(Integer id) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic Product() {\n\t\t\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getInfo() {\n\t\treturn info;\n\t}\n\n\tpublic void setInfo(String info) {\n\t\tthis.info = info;\n\t}\n\n\tpublic Float getGram() {\n\t\treturn gram;\n\t}\n\n\tpublic void setGram(Float gram) {\n\t\tthis.gram = gram;\n\t}\n\n\tpublic String getImgUrl() {\n\t\treturn imgUrl;\n\t}\n\n\tpublic void setImgUrl(String imgUrl) {\n\t\tthis.imgUrl = imgUrl;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Long getStock() {\n\t\treturn stock;\n\t}\n\n\tpublic void setStock(Long stock) {\n\t\tthis.stock = stock;\n\t}\n\n\tpublic String getTypeGram() {\n\t\treturn typeGram;\n\t}\n\n\tpublic void setTypeGram(String typeGram) {\n\t\tthis.typeGram = typeGram;\n\t}\n\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\tpublic void setUpdatedAt(LocalDateTime updatedAt) {\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Product [id=\" + id + \", name=\" + name + \", info=\" + info + \", gram=\" + gram\n\t\t\t\t+ \", imgUrl=\" + imgUrl + \", price=\" + price + \", stock=\" + stock + \", typeGram=\" + typeGram\n\t\t\t\t+ \", createdAt=\" + createdAt + \", updatedAt=\" + updatedAt + \"]\";\n\t}\n}" }, { "identifier": "Review", "path": "src/main/java/com/dulcenectar/java/models/Review.java", "snippet": "@Entity\n@Table(name = \"reviews\")\npublic class Review {\n\t\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\t@ManyToOne\n\t@JoinColumn(name = \"user_id\", nullable = false)\n\tprivate User user;\n\tprivate String review;\n\tprivate int rating;\n\t@ManyToOne\n\t@JoinColumn(name = \"product_id\", nullable = false)\n\tprivate Product product;\n\t\n\t@CreationTimestamp\n\tprivate LocalDateTime created_at;\n\t@UpdateTimestamp\n\tprivate LocalDateTime updated_at;\n\n\t\n\tpublic Review(Integer id, User user, String review, int rating, Product product, LocalDateTime created_at,\n\t\t\tLocalDateTime updated_at) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.user = user;\n\t\tthis.review = review;\n\t\tthis.rating = rating;\n\t\tthis.product = product;\n\t\tthis.created_at = created_at;\n\t\tthis.updated_at = updated_at;\n\t}\n\n\tpublic Review (Integer id) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic Review () {}\n\t\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic String getReview() {\n\t\treturn review;\n\t}\n\n\tpublic void setReview(String review) {\n\t\tthis.review = review;\n\t}\n\n\tpublic int getRating() {\n\t\treturn rating;\n\t}\n\n\tpublic void setRating(int rating) {\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Product getProduct() {\n\t\treturn product;\n\t}\n\n\tpublic void setProduct(Product product) {\n\t\tthis.product = product;\n\t}\n\n\tpublic LocalDateTime getCreated_at() {\n\t\treturn created_at;\n\t}\n\n\tpublic void setCreated_at(LocalDateTime created_at) {\n\t\tthis.created_at = created_at;\n\t}\n\n\tpublic LocalDateTime getUpdated_at() {\n\t\treturn updated_at;\n\t}\n\n\tpublic void setUpdated_at(LocalDateTime updated_at) {\n\t\tthis.updated_at = updated_at;\n\t}\n\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Review [id=\" + id + \", user=\" + user + \", review=\" + review + \", rating=\" + rating + \", product=\"\n\t\t\t\t+ product + \", created_at=\" + created_at + \", updated_at=\" + updated_at + \"]\";\n\t}\t\n}" }, { "identifier": "ProductRepository", "path": "src/main/java/com/dulcenectar/java/repositories/ProductRepository.java", "snippet": "public interface ProductRepository extends CrudRepository<Product, Integer> {\n\t\n\t}" }, { "identifier": "ReviewRepository", "path": "src/main/java/com/dulcenectar/java/repositories/ReviewRepository.java", "snippet": "public interface ReviewRepository extends CrudRepository <Review, Integer> {\n\t\n}" }, { "identifier": "UserDetailsImpl", "path": "src/main/java/com/dulcenectar/java/security/UserDetailsImpl.java", "snippet": "public class UserDetailsImpl extends User implements UserDetails {\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -1833377617454173091L;\n\t\n\tpublic UserDetailsImpl() {\n\t\tsuper();\n\t}\n\n\tpublic UserDetailsImpl(Integer id, String firstName, String lastName, String email, String password, Role role,\n\t\t\tLocalDateTime createdAt, LocalDateTime updatedAt) {\n\t\tsuper(id, firstName, lastName, email, password, role, createdAt, updatedAt);\n\t}\n\n\tpublic UserDetailsImpl(Integer id, String firstName, String lastName, String email, String password) {\n\t\tsuper(id, firstName, lastName, email, password);\n\t}\n\n\tpublic UserDetailsImpl(Integer id) {\n\t\tsuper(id);\n\t}\n\n\t@Override\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\n\t\treturn List.of(new SimpleGrantedAuthority((role.name())));\n\t}\n\n\t@Override\n\tpublic String getPassword() {\n\t\treturn this.getPassword();\n\t}\n\n\t@Override\n\tpublic String getUsername() {\n\t\treturn email;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonExpired() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonLocked() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isCredentialsNonExpired() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isEnabled() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UserDetailsImpl [id=\" + id + \", email=\" + email + \", password=\" + password + \", role=\" + role + \"]\";\n\t}\n\t\n}" }, { "identifier": "IReviewService", "path": "src/main/java/com/dulcenectar/java/services/interfaces/IReviewService.java", "snippet": "public interface IReviewService {\n\t\n\t\n\tpublic ArrayList<ResponseReviewDto> getReviews();\n\t\n\tpublic ResponseReviewDto saveReview(CreateReviewDto review);\n\t\n\tpublic ResponseReviewDto deleteReview( Integer id ); \n\t\n\tpublic ResponseReviewDto updateReview(Integer id, UpdateReviewDto review);\n\n\t\n}" } ]
import java.util.ArrayList; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import com.dulcenectar.java.dtos.review.CreateReviewDto; import com.dulcenectar.java.dtos.review.ResponseReviewDto; import com.dulcenectar.java.dtos.review.UpdateReviewDto; import com.dulcenectar.java.exceptions.ProductNotFoundException; import com.dulcenectar.java.exceptions.ReviewNotFoundException; import com.dulcenectar.java.models.Product; import com.dulcenectar.java.models.Review; import com.dulcenectar.java.repositories.ProductRepository; import com.dulcenectar.java.repositories.ReviewRepository; import com.dulcenectar.java.security.UserDetailsImpl; import com.dulcenectar.java.services.interfaces.IReviewService;
4,182
package com.dulcenectar.java.services; @Service public class ReviewServiceImpl implements IReviewService { @Autowired ReviewRepository reviewRepository; @Autowired ProductRepository productRepository; @Override public ArrayList<ResponseReviewDto> getReviews() { ArrayList<Review> reviewsList = (ArrayList<Review>)reviewRepository.findAll(); ArrayList<ResponseReviewDto> reviewsResponse = new ArrayList<>(); for(Review review: reviewsList) { ResponseReviewDto reviewResponseDto = new ResponseReviewDto(); reviewsResponse.add(reviewResponseDto.fromEntity(review)); } return reviewsResponse; } @Override public ResponseReviewDto saveReview(CreateReviewDto review) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl currentUser = (UserDetailsImpl)authentication.getPrincipal(); Optional<Product> product = productRepository.findById(review.getProductId()); if(product.isEmpty()) throw new ProductNotFoundException(); Review reviewEntity = review.toEntity(); reviewEntity.setProduct(product.get()); reviewEntity.setUser(currentUser); reviewRepository.save(reviewEntity); ResponseReviewDto response = new ResponseReviewDto(); return response.fromEntity(reviewEntity); } @Override public ResponseReviewDto deleteReview(Integer id) { Optional<Review> reviewCheck = reviewRepository.findById(id);
package com.dulcenectar.java.services; @Service public class ReviewServiceImpl implements IReviewService { @Autowired ReviewRepository reviewRepository; @Autowired ProductRepository productRepository; @Override public ArrayList<ResponseReviewDto> getReviews() { ArrayList<Review> reviewsList = (ArrayList<Review>)reviewRepository.findAll(); ArrayList<ResponseReviewDto> reviewsResponse = new ArrayList<>(); for(Review review: reviewsList) { ResponseReviewDto reviewResponseDto = new ResponseReviewDto(); reviewsResponse.add(reviewResponseDto.fromEntity(review)); } return reviewsResponse; } @Override public ResponseReviewDto saveReview(CreateReviewDto review) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl currentUser = (UserDetailsImpl)authentication.getPrincipal(); Optional<Product> product = productRepository.findById(review.getProductId()); if(product.isEmpty()) throw new ProductNotFoundException(); Review reviewEntity = review.toEntity(); reviewEntity.setProduct(product.get()); reviewEntity.setUser(currentUser); reviewRepository.save(reviewEntity); ResponseReviewDto response = new ResponseReviewDto(); return response.fromEntity(reviewEntity); } @Override public ResponseReviewDto deleteReview(Integer id) { Optional<Review> reviewCheck = reviewRepository.findById(id);
if(reviewCheck.isEmpty()) throw new ReviewNotFoundException();
4
2023-10-24 00:07:39+00:00
8k
DaveScott99/ToyStore-JSP
src/main/java/br/com/toyStore/servlet/Servlet.java
[ { "identifier": "CategoryDAO", "path": "src/main/java/br/com/toyStore/dao/CategoryDAO.java", "snippet": "public class CategoryDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Category category;\n\n\tpublic CategoryDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(Category category) {\n\t\ttry {\n\t\t\tif (category != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.CATEGORY (NAME_CATEGORY, IMAGE_NAME_CATEGORY) values (?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, category.getName());\n\t\t\t\tps.setString(2, category.getImageName());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Category category) {\n\t\ttry {\n\t\t\tif (category != null) {\n\t\t\t\tString SQL = \"UPDATE alunos set nome=?, email=?, endereco=?, datanascimento=?, \"\n\t\t\t\t\t\t+ \"periodo=? WHERE ra=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\t//ps.setString(1, aluno.getNome());\n\t\t\t\t//ps.setString(2, aluno.getEmail());\n\t\t\t\t//ps.setString(3, aluno.getEndereco());\n\t\t\t\t//ps.setDate(4, new java.sql.Date(aluno.getDataNascimento().getTime()));\n\t\t\t\t//ps.setString(5, aluno.getPeriodo());\n\t\t\t\t//ps.setInt(6, aluno.getRa());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idCategory) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic Category findByName(String idCategory) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT WHERE CAT.NAME_CATEGORY =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setString(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\t\t\t\n\t\t\t}\n\t\t\treturn category;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic Category findById(int idCategory) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT WHERE CAT.ID_CATEGORY =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\t\t\t}\n\t\t\treturn category;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Category> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT ORDER BY CAT.NAME_CATEGORY\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Category> list = new ArrayList<Category>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\n\t\t\t\tlist.add(category);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "ProductDAO", "path": "src/main/java/br/com/toyStore/dao/ProductDAO.java", "snippet": "public class ProductDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Product product;\n\n\tpublic ProductDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values \"\n\t\t\t\t\t\t+ \"(?, ?, ?, ?, ?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, product.getName());\n\t\t\t\tps.setDouble(2, product.getPrice());\n\t\t\t\tps.setString(3, product.getDescription());\n\t\t\t\tps.setString(4, product.getImageName());\n\t\t\t\tps.setString(5, product.getBrand());\n\t\t\t\tps.setLong(6, product.getCategory().getId());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, product.getName());\n\t\t\t\tps.setDouble(2, product.getPrice());\n\t\t\t\tps.setString(3, product.getDescription());\n\t\t\t\tps.setString(4, product.getImageName());\n\t\t\t\tps.setLong(5, product.getCategory().getId());\n\t\t\t\tps.setString(6, product.getBrand());\n\t\t\t\tps.setLong(7, product.getId());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idProduct) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idProduct);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic Product findById(int idProduct) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idProduct);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\n\t\t\t\tlong idCategory = rs.getInt(\"id_category\");\n\t\t\t\tString nameCategory = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\n\t\t\t\tproduct.setCategory(new Category(idCategory, nameCategory, imageCategory));\n\t\t\t}\n\t\t\treturn product;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Product> findProductsByCategory(int idCategory) {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_CATEGORY = ?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic List<Product> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\t\t\t\t\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Product> findAllForAdmin() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\n\t\t\t\tlong idCategory = rs.getInt(\"id_category\");\n\t\t\t\tString nameCategory = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setCategory(new Category(idCategory, nameCategory, imageCategory));\n\t\t\t\tproduct.setBrand(brand);\n\t\t\t\t\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "UserDAO", "path": "src/main/java/br/com/toyStore/dao/UserDAO.java", "snippet": "public class UserDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate User user;\n\n\tpublic UserDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(User user) {\n\t\ttry {\n\t\t\tif (user != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.USER (USERNAME_USER, PASSWORD_USER) values \"\n\t\t\t\t\t\t+ \"(?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, user.getUsername());\n\t\t\t\tps.setString(2, user.getPassword());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"UPDATE alunos set nome=?, email=?, endereco=?, datanascimento=?, \"\n\t\t\t\t\t\t+ \"periodo=? WHERE ra=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\t//ps.setString(1, aluno.getNome());\n\t\t\t\t//ps.setString(2, aluno.getEmail());\n\t\t\t\t//ps.setString(3, aluno.getEndereco());\n\t\t\t\t//ps.setDate(4, new java.sql.Date(aluno.getDataNascimento().getTime()));\n\t\t\t\t//ps.setString(5, aluno.getPeriodo());\n\t\t\t\t//ps.setInt(6, aluno.getRa());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idUser) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.USER AS PROD WHERE ID_USEr=?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idUser);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic User findByUsername(String username) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.USER WHERE USERNAME_USER = ?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setString(1, username);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tint id = rs.getInt(\"id_user\");\n\t\t\t\tString usernameUser = rs.getString(\"username_user\");\n\t\t\t\tString passwordUser = rs.getString(\"password_user\");\n\n\t\t\t\tuser = new User();\n\t\t\t\tuser.setId(id);\n\t\t\t\tuser.setUsername(usernameUser);\n\t\t\t\tuser.setPassword(passwordUser);\n\t\t\t}\n\t\t\treturn user;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic User findById(int idUser) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.USER WHERE ID_USER =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idUser);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tint id = rs.getInt(\"id_user\");\n\t\t\t\tString username = rs.getString(\"username_user\");\n\t\t\t\tString password = rs.getString(\"password_user\");\n\n\t\t\t\tuser.setId(id);\n\t\t\t\tuser.setUsername(username);\n\t\t\t\tuser.setPassword(password);\n\t\t\t}\n\t\t\treturn user;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic List<Product> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\t\n\t\t\t\t//product = new Product();\n\t\t\t\t//product.setId(id);\n\t\t\t\t//product.setName(name);\n\t\t\t\t//product.setPrice(price);\n\t\t\t\t//product.setDescription(description);\n\t\t\t\t\n\t\t\t\t//list.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "DbException", "path": "src/main/java/br/com/toyStore/exception/DbException.java", "snippet": "public class DbException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n}" }, { "identifier": "Category", "path": "src/main/java/br/com/toyStore/model/Category.java", "snippet": "public class Category {\n\n\tprivate Long id;\n\tprivate String name;\n\tprivate String imageName;\n\t\t\n\tpublic Category() {\n\t}\n\n\tpublic Category(Long id, String name, String imageName) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\t\n}" }, { "identifier": "Product", "path": "src/main/java/br/com/toyStore/model/Product.java", "snippet": "public class Product implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long id;\n\tprivate String name;\n\tprivate Double price;\n\tprivate String imageName;\n\tprivate String brand;\n\tprivate String description;\n\t\n\tprivate Category category;\n\t\n\tpublic Product() {\n\t}\n\n\tpublic Product(Long id, String name, Double price, String imageName, String brand, String description,\n\t\t\tCategory category) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.price = price;\n\t\tthis.imageName = imageName;\n\t\tthis.brand = brand;\n\t\tthis.description = description;\n\t\tthis.category = category;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic String getBrand() {\n\t\treturn brand;\n\t}\n\n\tpublic void setBrand(String brand) {\n\t\tthis.brand = brand;\n\t}\n\t\n}" }, { "identifier": "User", "path": "src/main/java/br/com/toyStore/model/User.java", "snippet": "public class User {\n\n\tprivate int id;\n\tprivate String username;\n\tprivate String password;\n\t\n\tpublic User() {\n\t}\n\t\n\tpublic User(int id, String username, String password) {\n\t\tthis.id = id;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t\n\t\n}" }, { "identifier": "ConnectionFactory", "path": "src/main/java/br/com/toyStore/util/ConnectionFactory.java", "snippet": "public class ConnectionFactory {\n\nprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\t\t\t\n\t\t\t\tString login = \"root\";\n\t\t\t\tString senha = \"1305\";\n\t\t\t\tString url = \"jdbc:mysql://localhost:3306/TOY_STORE?useUnicode=true&characterEncoding=UTF-8\";\n\t\t\t\tconn = DriverManager.getConnection(url,login,senha);\n\t\t\t}\n\t\t\tcatch(SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t} \n\t\t\tcatch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t}\n\t\n\tpublic static void closeConnection() {\n\t\tif (conn != null) {\n\t\t\ttry {\n\t\t\t\tconn.close();\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeStatement(Statement st) {\n\t\tif (st != null) {\n\t\t\ttry {\n\t\t\t\tst.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeResultSet(ResultSet rs) {\n\t\tif (rs != null) {\n\t\t\ttry {\n\t\t\t\trs.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt,\n\t\t\tResultSet rs) throws Exception {\n\t\tclose(conn, stmt, rs);\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt)\n\t\t\tthrows Exception {\n\t\tclose(conn, stmt, null);\n\t}\n\n\tpublic static void closeConnection(Connection conn) throws Exception {\n\t\tclose(conn, null, null);\n\t}\n\n\tprivate static void close(Connection conn, Statement stmt, ResultSet rs)\n\t\t\tthrows Exception {\n\t\ttry {\n\t\t\tif (rs != null)\n\t\t\t\trs.close();\n\t\t\tif (stmt != null)\n\t\t\t\tstmt.close();\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(e.getMessage());\n\t\t}\n\t}\n\t\n}" } ]
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import br.com.toyStore.dao.CategoryDAO; import br.com.toyStore.dao.ProductDAO; import br.com.toyStore.dao.UserDAO; import br.com.toyStore.exception.DbException; import br.com.toyStore.model.Category; import br.com.toyStore.model.Product; import br.com.toyStore.model.User; import br.com.toyStore.util.ConnectionFactory;
6,423
package br.com.toyStore.servlet; @WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories", "/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin", "/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"}) @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 100 // 100 MB ) public class Servlet extends HttpServlet { private static final long serialVersionUID = 1L; ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection()); CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection()); UserDAO userDao = new UserDAO(ConnectionFactory.getConnection()); Product product = new Product(); Category category = new Category(); final String IMAGES_PATH = "D:\\ARQUIVOS\\DevCompleto\\JAVA-WEB\\toy-store\\src\\main\\webapp\\assets\\"; public Servlet() throws Exception{ super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); if (action.equals("/home")) { findAllProducts(request, response); } else if (action.equals("/categories")) { findAllCategories(request, response); } else if (action.equals("/selectCategory")) { findAllProductsByCategory(request, response); } else if (action.equals("/selectProduct")) { selectProduct(request, response); } else if (action.equals("/insertProduct")) { insertProduct(request, response); } else if (action.equals("/login")) { login(request, response); } else if (action.equals("/admin")) { admin(request, response); } else if (action.equals("/selectProductUpdate")) { selectProductForUpdate(request, response); } else if (action.equals("/updateProduct")) { updateProduct(request, response); } else if (action.equals("/deleteProduct")) { deleteProduct(request, response); } else if (action.equals("/insertCategory")) { insertCategory(request, response); } else if (action.equals("/newProduct")) { newProduct(request, response); } } protected void newProduct(HttpServletRequest request, HttpServletResponse response) { try { List<Category> categories = categoryDao.findAll(); request.setAttribute("categories", categories); RequestDispatcher rd = request.getRequestDispatcher("newProduct.jsp"); rd.forward(request, response); } catch (Exception e) {
package br.com.toyStore.servlet; @WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories", "/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin", "/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"}) @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 100 // 100 MB ) public class Servlet extends HttpServlet { private static final long serialVersionUID = 1L; ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection()); CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection()); UserDAO userDao = new UserDAO(ConnectionFactory.getConnection()); Product product = new Product(); Category category = new Category(); final String IMAGES_PATH = "D:\\ARQUIVOS\\DevCompleto\\JAVA-WEB\\toy-store\\src\\main\\webapp\\assets\\"; public Servlet() throws Exception{ super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); if (action.equals("/home")) { findAllProducts(request, response); } else if (action.equals("/categories")) { findAllCategories(request, response); } else if (action.equals("/selectCategory")) { findAllProductsByCategory(request, response); } else if (action.equals("/selectProduct")) { selectProduct(request, response); } else if (action.equals("/insertProduct")) { insertProduct(request, response); } else if (action.equals("/login")) { login(request, response); } else if (action.equals("/admin")) { admin(request, response); } else if (action.equals("/selectProductUpdate")) { selectProductForUpdate(request, response); } else if (action.equals("/updateProduct")) { updateProduct(request, response); } else if (action.equals("/deleteProduct")) { deleteProduct(request, response); } else if (action.equals("/insertCategory")) { insertCategory(request, response); } else if (action.equals("/newProduct")) { newProduct(request, response); } } protected void newProduct(HttpServletRequest request, HttpServletResponse response) { try { List<Category> categories = categoryDao.findAll(); request.setAttribute("categories", categories); RequestDispatcher rd = request.getRequestDispatcher("newProduct.jsp"); rd.forward(request, response); } catch (Exception e) {
throw new DbException(e.getMessage());
3
2023-10-20 02:51:14+00:00
8k
yallerocha/Estruturas-de-Dados-e-Algoritmos
src/main/java/com/dataStructures/avltree/AVLTreeImpl.java
[ { "identifier": "BSTImpl", "path": "src/main/java/com/dataStructures/binarySearchTree/BSTImpl.java", "snippet": "public class BSTImpl<T extends Comparable<T>> implements BST<T> {\n\n\tprotected BSTNode<T> root;\n\n\tpublic BSTImpl() {\n\t\troot = new BSTNode<T>();\n\t\troot.setParent(new BSTNode<T>());\n\t}\n\t\n\tpublic BSTNode<T> getRoot() {\n\t\treturn this.root;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn root.isEmpty();\n\t}\n\n\t@Override\n\tpublic int height() {\n\t\treturn height(this.root);\n\t}\n\t\n\tpublic int height(BSTNode<T> node) {\n\t if(node.isEmpty()) {\n\t return -1;\n\t } \n\t int left = height((BSTNode<T>) node.getLeft());\n\t int right = height((BSTNode<T>) node.getRight());\n\t \n\t if(left > right) {\n\t \treturn left + 1;\n\t } else {\n\t \treturn right + 1;\n\t }\n\t}\n\n\tpublic int heightRecursive (BSTNode<T> currentNode) {\n\t\tint resp = -1;\n\n\t\tif (!currentNode.isEmpty()) {\n\t\t\tresp = 1 + Math.max(this.heightRecursive((BSTNode<T>) currentNode.getLeft()),\n\t\t\t\t\tthis.heightRecursive((BSTNode<T>) currentNode.getRight()));\n\t\t}\n\t\treturn resp;\n\t}\n\t\n\t@Override\n\tpublic BSTNode<T> search(T element) {\n\t\treturn search(this.root, element);\n\t}\n\t\n\tpublic BSTNode<T> search(BSTNode<T> node, T element) {\n\t\tif(node.isEmpty() || node.getData() == element) {\n\t\t\treturn node;\n\t\t} \n\t\tif (node.getData().compareTo(element) > 0) {\n\t\t\treturn search((BSTNode<T>) node.getLeft(), element);\n\t\t} else {\n\t\t\treturn search((BSTNode<T>) node.getRight(), element);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void insert(T element) {\n\t\tinsert(root, (BSTNode<T>) root.getParent(), element);\n\t}\n\t\n\tpublic void insert(BSTNode<T> node, BSTNode<T> parent, T element) {\n\t\tif(node.isEmpty()) {\n\t\t\tnode.setData(element);\n\t\t\tnode.setParent(parent);\n\t\t\tnode.setLeft(new BSTNode<T>());\n\t\t\tnode.setRight(new BSTNode<T>());\n\t\t} else {\n\t\t\tif(element.compareTo(node.getData()) < 0) {\n\t\t\t\tinsert((BSTNode<T>) node.getLeft(), node, element);\n\t\t\t} else {\n\t\t\t\tinsert((BSTNode<T>) node.getRight(), node, element);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic BSTNode<T> maximum() {\n\t\treturn maximum(this.root);\n\t}\n\t\n\tprivate BSTNode<T> maximum(BSTNode<T> node) {\n\t\tif(node.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\twhile(!node.getRight().isEmpty()) {\n\t\t\tnode = (BSTNode<T>) node.getRight();\n\t\t}\n\t\treturn node;\n\t}\n\n\t@Override\n\tpublic BSTNode<T> minimum() {\n\t\treturn minimum(this.root);\n\t}\n\t\n\tprivate BSTNode<T> minimum(BSTNode<T> node) {\n\t\tif(node.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\twhile(!node.getLeft().isEmpty()) {\n\t\t\tnode = (BSTNode<T>) node.getLeft();\n\t\t}\n\t\treturn node;\n\t}\n\t\n\t@Override\n\tpublic BSTNode<T> sucessor(T element) {\n\t\t\n\t\tBSTNode<T> node = search(element);\n\t\t\n\t\tif(node == maximum() || node.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\tif(!node.getRight().isEmpty()) {\n\t\t\treturn minimum((BSTNode<T>) node.getRight());\n\t\t} \n\t\treturn ancestralSuccessor(node);\n\t}\n\n\tprivate BSTNode<T> ancestralSuccessor(BSTNode<T> node) {\n\t\tBSTNode<T> father = (BSTNode<T>) node.getParent();\n\t\t\n\t\twhile(!father.isEmpty() && node == father.getRight()) {\n\t\t\tnode = father;\n\t\t\tfather = (BSTNode<T>) father.getParent();\n\t\t}\n\t\treturn father;\n\t}\n\n\t@Override\n\tpublic BSTNode<T> predecessor(T element) {\n\t\t\n\t\tBSTNode<T> node = search(element);\n\t\t\n\t\tif(node == minimum() || node.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\tif(!node.getLeft().isEmpty()) {\n\t\t\treturn maximum((BSTNode<T>) node.getLeft());\n\t\t}\n\t\treturn ancestralPredecessor(node);\t\n\t}\n\t\n\tprivate BSTNode<T> ancestralPredecessor(BSTNode<T> node) {\n\t\tBSTNode<T> father = (BSTNode<T>) node.getParent();\n\t\t\n\t\twhile(!father.isEmpty() && node == father.getLeft()) {\n\t\t\tnode = father;\n\t\t\tfather = (BSTNode<T>) father.getParent();\n\t\t}\n\t\treturn father;\n\t}\n\n\t@Override\n\tpublic void remove(T element) {\n\t\tBSTNode<T> node = search(element);\n\t\tremove(node);\n\t}\n\tprivate void remove(BSTNode<T> node) {\n\n\t\tif(!node.isEmpty()) {\n\t\t\tif(node.isLeaf()) {\n\t\t\t\tnode.setData(null);\n\t\t\t\tnode.setParent(null);\n\t\t\t} else if (nodeHasOneChild(node)) {\n\t\t\t\tif(node != this.root) {\n\t\t\t\t\tif(nodeIsLeftChild(node)) {\n\t\t\t\t\t\tif(!node.getLeft().isEmpty()) {\n\t\t\t\t\t\t\tnode.getParent().setLeft(node.getLeft());\n\t\t\t\t\t\t\tnode.getLeft().setParent(node.getParent());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnode.getParent().setLeft(node.getRight());\n\t\t\t\t\t\t\tnode.getRight().setParent(node.getParent());\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(!node.getLeft().isEmpty()) {\n\t\t\t\t\t\t\tnode.getParent().setRight(node.getLeft());\n\t\t\t\t\t\t\tnode.getLeft().setParent(node.getParent());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnode.getParent().setRight(node.getRight());\n\t\t\t\t\t\t\tnode.getRight().setParent(node.getParent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif(!node.getLeft().isEmpty()) {\n\t\t\t\t\t\tthis.root = (BSTNode<T>) node.getLeft();\n\t\t\t\t\t\tthis.root.setParent(new BSTNode<T>());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.root = (BSTNode<T>) node.getRight();\n\t\t\t\t\t\tthis.root.setParent(new BSTNode<T>());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tBSTNode<T> sucessor = sucessor(node.getData());\n\t\t\t\tnode.setData(sucessor.getData());\n\t\t\t\tremove(sucessor);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate Boolean nodeHasOneChild(BSTNode<T> node) {\n\t\treturn node.getLeft().isEmpty() && !node.getRight().isEmpty() || \n\t\t\t\t!node.getLeft().isEmpty() && node.getRight().isEmpty();\n\t}\n\t\n\tprivate Boolean nodeIsLeftChild(BSTNode<T> node) {\n\t\tBSTNode<T> father = (BSTNode<T>) node.getParent();\n\t\treturn father.getLeft() == node;\n\t}\n\n\t@Override\n\tpublic T[] preOrder() {\n\t\tList<T> list = new ArrayList<T>();\n\t\tpreOrder(this.root, list);\n\t\treturn listToArray(list);\n\t}\n\t\n\tprivate void preOrder(BSTNode<T> node, List<T> list) {\n\t\tif(!node.isEmpty()) {\n\t\t\tvisit(node, list);\n\t\t\tpreOrder((BSTNode<T>) node.getLeft(), list);\n\t\t\tpreOrder((BSTNode<T>) node.getRight(), list);\n\t\t}\n\t}\n\t\n\tprivate void visit(BSTNode<T> node, List<T> list) {\n\t\tlist.add(node.getData());\n\t}\n\t\n\tprivate T[] listToArray(List<T> list) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] array = (T[]) new Comparable[size()];\n\t\t\n\t\tint index = 0;\n\t\tfor(T data: list) {\n\t\t\tarray[index] = data;\n\t\t\tindex++;\n\t\t}\n\t\treturn array;\n\t}\n\n\t@Override\n\tpublic T[] order() {\n\t\tList<T> list = new ArrayList<T>();\n\t\torder(this.root, list);\n\t\treturn listToArray(list);\n\t}\n\t\n\tprivate void order(BSTNode<T> node, List<T> list) {\n\t\tif(!node.isEmpty()) {\n\t\t\torder((BSTNode<T>) node.getLeft(), list);\n\t\t\tvisit(node, list);\n\t\t\torder((BSTNode<T>) node.getRight(), list);\n\t\t}\n\t}\n\n\t@Override\n\tpublic T[] postOrder() {\n\t\tList<T> list = new ArrayList<T>();\n\t\tpostOrder(this.root, list);\n\t\treturn listToArray(list);\n\t}\n\t\n\tprivate void postOrder(BSTNode<T> node, List<T> list) {\n\t\tif(!node.isEmpty()) {\n\t\t\tpostOrder((BSTNode<T>) node.getLeft(), list);\n\t\t\tpostOrder((BSTNode<T>) node.getRight(), list);\n\t\t\tvisit(node, list);\n\t\t}\n\t}\n\t\n\t/**\n\t * This method is already implemented using recursion. You must understand\n\t * how it work and use similar idea with the other methods.\n\t */\n\t@Override\n\tpublic int size() {\n\t\treturn size(root);\n\t}\n\n\tprivate int size(BSTNode<T> node) {\n\t\tint result = 0;\n\t\t// base case means doing nothing (return 0)\n\t\tif (!node.isEmpty()) { // indusctive case\n\t\t\tresult = 1 + size((BSTNode<T>) node.getLeft())\n\t\t\t\t\t+ size((BSTNode<T>) node.getRight());\n\t\t}\n\t\treturn result;\n\t}\n\n}" }, { "identifier": "BSTNode", "path": "src/main/java/com/dataStructures/binarySearchTree/BSTNode.java", "snippet": "public class BSTNode<T extends Comparable<T>> extends BTNode<T> {\n\t\n\tpublic BSTNode() {\n\t\tsuper();\n\t}\n\n\t//código abaixo é um exempo de uso do padrão Builder para construir\n\t//objetos do tipo BSTNode sem usar construtor diretamente.\n\t//o código cliente desse padrao, criando o no vazio seria:\n\t// \t\tBSTNode<Integer> node = (BSTNode<Integer>) new BSTNode.Builder<Integer>()\n\t//\t\t\t.data(null)\n\t//\t\t\t.left(null)\n\t//\t\t\t.right(null)\n\t//\t\t\t.parent(null)\n\t//\t\t\t.build();\n\t\n\tpublic static class Builder<T>{\n\t\tT data;\n\t\tBTNode<T> left;\n\t\tBTNode<T> right;\n\t\tBTNode<T> parent;\n\t \n\t public BSTNode.Builder<T> data(T data){\n\t this.data = data;\n\t return this;\n\t }\n\t \n\t public BSTNode.Builder<T> left(BTNode<T> left){\n\t this.left = left;\n\t return this;\n\t }\n\t \n\t public BSTNode.Builder<T> right(BTNode<T> right){\n\t\t this.right = right;\n\t\t return this;\n\t\t}\n\t \n\t public BSTNode.Builder<T> parent(BTNode<T> parent){\n\t\t this.parent = parent;\n\t\t return this;\n\t\t}\n\t \n\t public BSTNode build(){\n\t \treturn new BSTNode(this);\n\t }\n\t }\n\tprivate BSTNode(BSTNode.Builder<T> builder){\n\t this.data = builder.data;\n\t this.left = builder.left;\n\t this.right = builder.right;\n\t this.parent = builder.parent;\n\t \n\t}\n}" }, { "identifier": "UtilRotation", "path": "src/main/java/com/dataStructures/binarySearchTree/binaryTree/UtilRotation.java", "snippet": "public class UtilRotation {\n\n\t/**\n\t * A rotacao a esquerda em node deve subir e retornar seu filho a direita\n\t * @param node\n\t * @return - noh que se tornou a nova raiz\n\t */\n\tpublic static <T extends Comparable<T>> BSTNode<T> leftRotation (BSTNode<T> node) {\n\t\tBSTNode<T> pivot = (BSTNode<T>) node.getRight();\n\t\n\t\tnode.setRight(pivot.getLeft());\n\t\tpivot.setLeft(node);\n\t\n\t\tpivot.setParent(node.getParent());\n\t\tnode.setParent(pivot);\n\t\tif (node.getRight() != null) {\n\t\t\tnode.getRight().setParent(node);\n\t\t}\n\t\n\t\tif (pivot.getParent() != null) {\n\t\t\tif (pivot.getParent().getRight() != null && pivot.getParent().getRight().equals(node)) {\n\t\t\t\tpivot.getParent().setRight(pivot);\n\t\t\t} else {\n\t\t\t\tpivot.getParent().setLeft(pivot);\n\t\t\t}\n\t\t}\n\t\treturn pivot;\n\t}\n\t\n\n\t/**\n\t * A rotacao a direita em node deve subir e retornar seu filho a esquerda\n\t * @param node\n\t * @return noh que se tornou a nova raiz\n\t */\n\tpublic static <T extends Comparable<T>> BSTNode<T> rightRotation (BSTNode<T> node) {\n\t\tBSTNode<T> pivot = (BSTNode<T>) node.getLeft();\n\t\n\t\tif (pivot != null) {\n\t\t\tnode.setLeft(pivot.getRight());\n\t\t\tif (pivot.getRight() != null) {\n\t\t\t\tpivot.getRight().setParent(node);\n\t\t\t}\n\t\t\tpivot.setRight(node);\n\t\n\t\t\tpivot.setParent(node.getParent());\n\t\t\tnode.setParent(pivot);\n\t\t\tif (node.getLeft() != null) {\n\t\t\t\tnode.getLeft().setParent(node);\n\t\t\t}\n\t\n\t\t\tif (pivot.getParent() != null) {\n\t\t\t\tif (pivot.getParent().getLeft() != null && pivot.getParent().getLeft().equals(node)) {\n\t\t\t\t\tpivot.getParent().setLeft(pivot);\n\t\t\t\t} else if (pivot.getParent().getRight() != null) {\n\t\t\t\t\tpivot.getParent().setRight(pivot);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pivot;\n\t}\n\t\n\t\n\tpublic static <T extends Comparable<T>> BSTNode<T> doubleLeftRotation (BSTNode<T> node) {\n\t\trightRotation((BSTNode<T>) node.getRight());\n\t\treturn leftRotation(node);\n\t}\n\n\tpublic static <T extends Comparable<T>> BSTNode<T> doubleRightRotation (BSTNode<T> node) {\n\t\tleftRotation((BSTNode<T>) node.getLeft());\n\t\treturn rightRotation(node);\n\t}\n\n\tpublic static <T extends Comparable<T>> T[] makeArrayOfComparable (int size) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tT[] array = (T[]) new Comparable[size];\n\t\treturn array;\n\t}\n}" } ]
import com.dataStructures.binarySearchTree.BSTImpl; import com.dataStructures.binarySearchTree.BSTNode; import com.dataStructures.binarySearchTree.binaryTree.UtilRotation;
3,820
package com.dataStructures.avltree; /** * * Implementacao de uma arvore AVL * A CLASSE AVLTree herda de BSTImpl. VOCE PRECISA SOBRESCREVER A IMPLEMENTACAO * DE BSTIMPL RECEBIDA COM SUA IMPLEMENTACAO "OU ENTAO" IMPLEMENTAR OS SEGUITNES * METODOS QUE SERAO TESTADOS NA CLASSE AVLTREE: * - insert * - preOrder * - postOrder * - remove * - height * - size * * @author Claudio Campelo * * @param <T> */ public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> { // TODO Do not forget: you must override the methods insert and remove // conveniently. // AUXILIARY public int calculateBalance (BSTNode<T> node) { int resp = 0; if (!node.isEmpty()) { resp = this.heightRecursive((BSTNode<T>) node.getLeft()) - this.heightRecursive((BSTNode<T>) node.getRight()); } return resp; } // AUXILIARY protected void rebalance (BSTNode<T> node) { BSTNode<T> newRoot = null; int balance = this.calculateBalance(node); if (Math.abs(balance) > 1) { if (balance > 1) { if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) {
package com.dataStructures.avltree; /** * * Implementacao de uma arvore AVL * A CLASSE AVLTree herda de BSTImpl. VOCE PRECISA SOBRESCREVER A IMPLEMENTACAO * DE BSTIMPL RECEBIDA COM SUA IMPLEMENTACAO "OU ENTAO" IMPLEMENTAR OS SEGUITNES * METODOS QUE SERAO TESTADOS NA CLASSE AVLTREE: * - insert * - preOrder * - postOrder * - remove * - height * - size * * @author Claudio Campelo * * @param <T> */ public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> { // TODO Do not forget: you must override the methods insert and remove // conveniently. // AUXILIARY public int calculateBalance (BSTNode<T> node) { int resp = 0; if (!node.isEmpty()) { resp = this.heightRecursive((BSTNode<T>) node.getLeft()) - this.heightRecursive((BSTNode<T>) node.getRight()); } return resp; } // AUXILIARY protected void rebalance (BSTNode<T> node) { BSTNode<T> newRoot = null; int balance = this.calculateBalance(node); if (Math.abs(balance) > 1) { if (balance > 1) { if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) {
newRoot = UtilRotation.rightRotation(node);
2
2023-10-21 21:39:25+00:00
8k
MYSTD/BigDataApiTest
data-governance-assessment/src/main/java/com/std/dga/governance/service/impl/GovernanceAssessDetailServiceImpl.java
[ { "identifier": "Assessor", "path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java", "snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n GovernanceAssessDetail governanceAssessDetail = new GovernanceAssessDetail();\n governanceAssessDetail.setAssessDate(assessParam.getAssessDate());\n governanceAssessDetail.setMetricId(assessParam.getTableMetaInfo().getId()+\"\");\n governanceAssessDetail.setTableName(assessParam.getTableMetaInfo().getTableName());\n governanceAssessDetail.setSchemaName(assessParam.getTableMetaInfo().getSchemaName());\n governanceAssessDetail.setMetricName(assessParam.getGovernanceMetric().getMetricName());\n governanceAssessDetail.setGovernanceType(assessParam.getGovernanceMetric().getGovernanceType());\n governanceAssessDetail.setTecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName());\n governanceAssessDetail.setCreateTime(new Date());\n //默认先给满分, 在考评器查找问题的过程中,如果有问题,再按照指标的要求重新给分。\n governanceAssessDetail.setAssessScore(BigDecimal.TEN);\n\n try {\n checkProblem(governanceAssessDetail, assessParam);\n }catch (Exception e) {\n governanceAssessDetail.setAssessScore(BigDecimal.ZERO);\n governanceAssessDetail.setIsAssessException(\"1\");\n //记录异常信息\n //简单记录\n //governanceAssessDetail.setAssessExceptionMsg( e.getMessage());\n\n //详细记录\n StringWriter stringWriter = new StringWriter() ;\n PrintWriter msgPrintWriter = new PrintWriter(stringWriter) ;\n e.printStackTrace( msgPrintWriter);\n governanceAssessDetail.setAssessExceptionMsg( stringWriter.toString().substring( 0, Math.min( 2000 , stringWriter.toString().length())) );\n }\n\n return governanceAssessDetail;\n }\n\n public abstract void checkProblem(GovernanceAssessDetail governanceAssessDetail , AssessParam assessParam) throws Exception;\n}" }, { "identifier": "TDsTaskDefinition", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskDefinition.java", "snippet": "@Data\n@TableName(\"t_ds_task_definition\")\npublic class TDsTaskDefinition implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * self-increasing id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * encoding\n */\n private Long code;\n\n /**\n * task definition name\n */\n private String name;\n\n /**\n * task definition version\n */\n private Integer version;\n\n /**\n * description\n */\n private String description;\n\n /**\n * project code\n */\n private Long projectCode;\n\n /**\n * task definition creator id\n */\n private Integer userId;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * job priority\n */\n private Byte taskPriority;\n\n /**\n * worker grouping\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * number of failed retries\n */\n private Integer failRetryTimes;\n\n /**\n * failed retry interval\n */\n private Integer failRetryInterval;\n\n /**\n * timeout flag:0 close, 1 open\n */\n private Byte timeoutFlag;\n\n /**\n * timeout notification policy: 0 warning, 1 fail\n */\n private Byte timeoutNotifyStrategy;\n\n /**\n * timeout length,unit: minute\n */\n private Integer timeout;\n\n /**\n * delay execution time,unit: minute\n */\n private Integer delayTime;\n\n /**\n * resource id, separated by comma\n */\n private String resourceIds;\n\n /**\n * create time\n */\n private Date createTime;\n\n /**\n * update time\n */\n private Date updateTime;\n\n @TableField(exist = false)\n private String taskSql; // 任务SQL\n}" }, { "identifier": "TDsTaskInstance", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskInstance.java", "snippet": "@Data\n@TableName(\"t_ds_task_instance\")\npublic class TDsTaskInstance implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * key\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * task name\n */\n private String name;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * task definition code\n */\n private Long taskCode;\n\n /**\n * task definition version\n */\n private Integer taskDefinitionVersion;\n\n /**\n * process instance id\n */\n private Integer processInstanceId;\n\n /**\n * Status: 0 commit succeeded, 1 running, 2 prepare to pause, 3 pause, 4 prepare to stop, 5 stop, 6 fail, 7 succeed, 8 need fault tolerance, 9 kill, 10 wait for thread, 11 wait for dependency to complete\n */\n private Byte state;\n\n /**\n * task submit time\n */\n private Date submitTime;\n\n /**\n * task start time\n */\n private Date startTime;\n\n /**\n * task end time\n */\n private Date endTime;\n\n /**\n * host of task running on\n */\n private String host;\n\n /**\n * task execute path in the host\n */\n private String executePath;\n\n /**\n * task log path\n */\n private String logPath;\n\n /**\n * whether alert\n */\n private Byte alertFlag;\n\n /**\n * task retry times\n */\n private Integer retryTimes;\n\n /**\n * pid of task\n */\n private Integer pid;\n\n /**\n * yarn app id\n */\n private String appLink;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * retry interval when task failed \n */\n private Integer retryInterval;\n\n /**\n * max retry times\n */\n private Integer maxRetryTimes;\n\n /**\n * task instance priority:0 Highest,1 High,2 Medium,3 Low,4 Lowest\n */\n private Integer taskInstancePriority;\n\n /**\n * worker group id\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * this config contains many environment variables config\n */\n private String environmentConfig;\n\n private Integer executorId;\n\n /**\n * task first submit time\n */\n private Date firstSubmitTime;\n\n /**\n * task delay execution time\n */\n private Integer delayTime;\n\n /**\n * var_pool\n */\n private String varPool;\n\n /**\n * dry run flag: 0 normal, 1 dry run\n */\n private Byte dryRun;\n}" }, { "identifier": "TDsTaskDefinitionService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskDefinitionService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskDefinitionService extends IService<TDsTaskDefinition> {\n\n List<TDsTaskDefinition> selectList();\n\n}" }, { "identifier": "TDsTaskInstanceService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskInstanceService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskInstanceService extends IService<TDsTaskInstance> {\n\n List<TDsTaskInstance> selectList(String assessDate);\n\n List<TDsTaskInstance> selectFailedTask(String taskName, String assessDate);\n\n List<TDsTaskInstance> selectBeforeNDaysInstance(String taskName, String startDate, String assessDate);\n}" }, { "identifier": "AssessParam", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java", "snippet": "@Data\npublic class AssessParam {\n\n private String assessDate ;\n private TableMetaInfo tableMetaInfo ;\n private GovernanceMetric governanceMetric ;\n\n private Map<String ,TableMetaInfo> tableMetaInfoMap ; // 所有表\n\n private TDsTaskDefinition tDsTaskDefinition ; // 该指标需要的任务定义\n\n private TDsTaskInstance tDsTaskInstance ; // 该指标需要的任务状态信息(当日)\n\n}" }, { "identifier": "GovernanceAssessDetail", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetail.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetail implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 指标项id\n */\n private String metricId;\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n /**\n * 考评得分\n */\n private BigDecimal assessScore;\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n /**\n * 考评备注\n */\n private String assessComment;\n\n /**\n * 考评是否异常\n */\n private String isAssessException;\n\n /**\n * 异常信息\n */\n private String assessExceptionMsg;\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n\n /**\n * 创建日期\n */\n private Date createTime;\n}" }, { "identifier": "GovernanceAssessDetailVO", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetailVO.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetailVO {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n}" }, { "identifier": "GovernanceMetric", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceMetric.java", "snippet": "@Data\n@TableName(\"governance_metric\")\npublic class GovernanceMetric implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 指标名称\n */\n private String metricName;\n\n /**\n * 指标编码\n */\n private String metricCode;\n\n /**\n * 指标描述\n */\n private String metricDesc;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 指标参数\n */\n private String metricParamsJson;\n\n /**\n * 治理连接\n */\n private String governanceUrl;\n\n /**\n * 跳过考评的表名(多表逗号分割)\n */\n private String skipAssessTables;\n\n /**\n * 是否启用\n */\n private String isDisabled;\n}" }, { "identifier": "GovernanceAssessDetailMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/mapper/GovernanceAssessDetailMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface GovernanceAssessDetailMapper extends BaseMapper<GovernanceAssessDetail> {\n\n}" }, { "identifier": "GovernanceAssessDetailService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceAssessDetailService.java", "snippet": "public interface GovernanceAssessDetailService extends IService<GovernanceAssessDetail> {\n\n void mainAssess( String assessDate);\n\n List<GovernanceAssessDetailVO> getProblemList(String governanceType, Integer pageNo, Integer pageSize);\n\n Map<String, Long> getProblemNum();\n}" }, { "identifier": "GovernanceMetricService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceMetricService.java", "snippet": "public interface GovernanceMetricService extends IService<GovernanceMetric> {\n\n}" }, { "identifier": "TableMetaInfo", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/bean/TableMetaInfo.java", "snippet": "@Data\n@TableName(\"table_meta_info\")\npublic class TableMetaInfo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 表id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 字段名json ( 来源:hive)\n */\n private String colNameJson;\n\n /**\n * 分区字段名json( 来源:hive)\n */\n private String partitionColNameJson;\n\n /**\n * hdfs所属人 ( 来源:hive)\n */\n private String tableFsOwner;\n\n /**\n * 参数信息 ( 来源:hive)\n */\n private String tableParametersJson;\n\n /**\n * 表备注 ( 来源:hive)\n */\n private String tableComment;\n\n /**\n * hdfs路径 ( 来源:hive)\n */\n private String tableFsPath;\n\n /**\n * 输入格式( 来源:hive)\n */\n private String tableInputFormat;\n\n /**\n * 输出格式 ( 来源:hive)\n */\n private String tableOutputFormat;\n\n /**\n * 行格式 ( 来源:hive)\n */\n private String tableRowFormatSerde;\n\n /**\n * 表创建时间 ( 来源:hive)\n */\n private Date tableCreateTime;\n\n /**\n * 表类型 ( 来源:hive)\n */\n private String tableType;\n\n /**\n * 分桶列 ( 来源:hive)\n */\n private String tableBucketColsJson;\n\n /**\n * 分桶个数 ( 来源:hive)\n */\n private Long tableBucketNum;\n\n /**\n * 排序列 ( 来源:hive)\n */\n private String tableSortColsJson;\n\n /**\n * 数据量大小 ( 来源:hdfs)\n */\n private Long tableSize=0L;\n\n /**\n * 所有副本数据总量大小 ( 来源:hdfs)\n */\n private Long tableTotalSize=0L;\n\n /**\n * 最后修改时间 ( 来源:hdfs)\n */\n private Date tableLastModifyTime;\n\n /**\n * 最后访问时间 ( 来源:hdfs)\n */\n private Date tableLastAccessTime;\n\n /**\n * 当前文件系统容量 ( 来源:hdfs)\n */\n private Long fsCapcitySize;\n\n /**\n * 当前文件系统使用量 ( 来源:hdfs)\n */\n private Long fsUsedSize;\n\n /**\n * 当前文件系统剩余量 ( 来源:hdfs)\n */\n private Long fsRemainSize;\n\n /**\n * 考评日期 \n */\n private String assessDate;\n\n /**\n * 创建时间 (自动生成)\n */\n private Date createTime;\n\n /**\n * 更新时间 (自动生成)\n */\n private Date updateTime;\n\n\n /**\n * 额外辅助信息\n */\n @TableField(exist = false)\n private TableMetaInfoExtra tableMetaInfoExtra;\n\n}" }, { "identifier": "TableMetaInfoMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/mapper/TableMetaInfoMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface TableMetaInfoMapper extends BaseMapper<TableMetaInfo> {\n\n @Select(\n \"SELECT ti.*, te.* , ti.id ti_id , te.id te_id\\n\" +\n \"FROM table_meta_info ti JOIN table_meta_info_extra te\\n\" +\n \"ON ti.schema_name = te.schema_name AND ti.table_name = te.table_name \\n\" +\n \"WHERE ti.assess_date = #{assessDate} \"\n )\n @ResultMap(\"meta_result_map\")\n List<TableMetaInfo> selectTableMetaInfoList(String assessDate);\n\n @Select(\"${sql}\")\n List<TableMetaInfoVO> selectTableMetaInfoVoList(String sql);\n @Select(\"${sql}\")\n Integer selectTableMetaInfoCount(String sql);\n}" }, { "identifier": "SpringBeanProvider", "path": "data-governance-assessment/src/main/java/com/std/dga/util/SpringBeanProvider.java", "snippet": "@Component\npublic class SpringBeanProvider implements ApplicationContextAware {\n\n ApplicationContext applicationContext ;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext ;\n }\n\n /**\n * 通过组件的名字,从容器中获取到对应的组件对象\n */\n public <T> T getBeanByName(String beanName , Class<T> tClass){\n T bean = applicationContext.getBean(beanName, tClass);\n return bean ;\n }\n}" } ]
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.std.dga.assessor.Assessor; import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition; import com.std.dga.dolphinscheduler.bean.TDsTaskInstance; import com.std.dga.dolphinscheduler.service.TDsTaskDefinitionService; import com.std.dga.dolphinscheduler.service.TDsTaskInstanceService; import com.std.dga.governance.bean.AssessParam; import com.std.dga.governance.bean.GovernanceAssessDetail; import com.std.dga.governance.bean.GovernanceAssessDetailVO; import com.std.dga.governance.bean.GovernanceMetric; import com.std.dga.governance.mapper.GovernanceAssessDetailMapper; import com.std.dga.governance.service.GovernanceAssessDetailService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.std.dga.governance.service.GovernanceMetricService; import com.std.dga.meta.bean.TableMetaInfo; import com.std.dga.meta.mapper.TableMetaInfoMapper; import com.std.dga.util.SpringBeanProvider; import com.sun.codemodel.internal.JForEach; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
5,259
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga") public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService { @Autowired TableMetaInfoMapper tableMetaInfoMapper; @Autowired
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga") public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService { @Autowired TableMetaInfoMapper tableMetaInfoMapper; @Autowired
GovernanceMetricService governanceMetricService;
11
2023-10-20 10:13:43+00:00
8k
RaulGB88/MOD-034-Microservicios-con-Java
REM20231023/catalogo/src/main/java/com/example/application/services/CatalogoServiceImpl.java
[ { "identifier": "FilmResource", "path": "REM20231023/catalogo/src/main/java/com/example/application/resources/FilmResource.java", "snippet": "@RestController\n@Tag(name = \"peliculas-service\", description = \"Mantenimiento de peliculas\")\n@RequestMapping(path = \"/peliculas/v1\")\npublic class FilmResource {\n\t@Autowired\n\tprivate FilmService srv;\n\t@Autowired\n\tDomainEventService deSrv;\n\n\t@Hidden\n\t@GetMapping(params = \"page\")\n\tpublic Page<FilmShortDTO> getAll(Pageable pageable,\n\t\t\t@RequestParam(defaultValue = \"short\") String mode) {\n\t\treturn srv.getByProjection(pageable, FilmShortDTO.class);\n\t}\n\n\t@Operation(\n\t\t\tsummary = \"Listado de las peliculas\", \n\t\t\tdescription = \"Recupera la lista de peliculas en formato corto o detallado, se puede paginar.\", \n\t\t\tparameters = {\n\t\t\t\t\t@Parameter(in = ParameterIn.QUERY, name = \"mode\", required = false, description = \"Formato de las peliculas\", schema = @Schema(type = \"string\", allowableValues = {\n\t\t\t\t\t\"details\", \"short\" }, defaultValue = \"short\")) },\n\t\t\tresponses = {\n\t\t\t\t\t@ApiResponse(responseCode = \"200\", description = \"OK\", content = \n\t\t\t\t\t\t\t@Content(mediaType = \"application/json\", schema = @Schema(anyOf = {FilmShortDTO.class, FilmDetailsDTO.class}) ))\n\t\t\t})\n\t@GetMapping(params = { \"page\", \"mode=details\" })\n\t@PageableAsQueryParam\n\t@Transactional\n\tpublic Page<FilmDetailsDTO> getAllDetailsPage(@Parameter(hidden = true) Pageable pageable,\n\t\t\t@RequestParam(defaultValue = \"short\") String mode) {\n\t\tvar content = srv.getAll(pageable);\n\t\treturn new PageImpl<>(content.getContent().stream().map(item -> FilmDetailsDTO.from(item)).toList(), pageable,\n\t\t\t\tcontent.getTotalElements());\n\t}\n\n\t@Hidden\n\t@GetMapping\n\tpublic List<FilmShortDTO> getAll(@RequestParam(defaultValue = \"short\") String mode) {\n\t\treturn srv.getByProjection(FilmShortDTO.class);\n\t}\n\n\t@Hidden\n\t@GetMapping(params = \"mode=details\")\n\tpublic List<FilmDetailsDTO> getAllDetails(\n//\t\t\t@Parameter(allowEmptyValue = true, required = false, schema = @Schema(type = \"string\", allowableValues = {\"details\",\"short\"}, defaultValue = \"short\")) \n\t\t\t@RequestParam(defaultValue = \"short\") String mode) {\n\t\treturn srv.getAll().stream().map(item -> FilmDetailsDTO.from(item)).toList();\n\t}\n\n\t@GetMapping(path = \"/{id}\", params = \"mode=short\")\n\tpublic FilmShortDTO getOneCorto(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id,\n\t\t\t@Parameter(required = false, allowEmptyValue = true, schema = @Schema(type = \"string\", allowableValues = {\n\t\t\t\t\t\"details\", \"short\",\n\t\t\t\t\t\"edit\" }, defaultValue = \"edit\")) @RequestParam(required = false, defaultValue = \"edit\") String mode)\n\t\t\tthrows Exception {\n\t\tOptional<Film> rslt = srv.getOne(id);\n\t\tif (rslt.isEmpty())\n\t\t\tthrow new NotFoundException();\n\t\treturn FilmShortDTO.from(rslt.get());\n\t}\n\n\t@GetMapping(path = \"/{id}\", params = \"mode=details\")\n\tpublic FilmDetailsDTO getOneDetalle(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id,\n\t\t\t@Parameter(required = false, schema = @Schema(type = \"string\", allowableValues = { \"details\", \"short\",\n\t\t\t\t\t\"edit\" }, defaultValue = \"edit\")) @RequestParam(required = false, defaultValue = \"edit\") String mode)\n\t\t\tthrows Exception {\n\t\tOptional<Film> rslt = srv.getOne(id);\n\t\tif (rslt.isEmpty())\n\t\t\tthrow new NotFoundException();\n\t\treturn FilmDetailsDTO.from(rslt.get());\n\t}\n\n\t@Operation(summary = \"Recupera una pelicula\", description = \"Están disponibles una versión corta, una versión con los detalles donde se han transformado las dependencias en cadenas y una versión editable donde se han transformado las dependencias en sus identificadores.\")\n\t@GetMapping(path = \"/{id}\")\n\t@ApiResponse(responseCode = \"200\", description = \"Pelicula encontrada\", content = @Content(schema = @Schema(oneOf = {\n\t\t\tFilmShortDTO.class, FilmDetailsDTO.class, FilmEditDTO.class })))\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\", content = @Content(schema = @Schema(implementation = ProblemDetail.class)))\n\tpublic FilmEditDTO getOneEditar(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id,\n\t\t\t@Parameter(required = false, schema = @Schema(type = \"string\", allowableValues = { \"details\", \"short\",\n\t\t\t\t\t\"edit\" }, defaultValue = \"edit\")) @RequestParam(required = false, defaultValue = \"edit\") String mode)\n\t\t\tthrows Exception {\n\t\tOptional<Film> rslt = srv.getOne(id);\n\t\tif (rslt.isEmpty())\n\t\t\tthrow new NotFoundException();\n\t\treturn FilmEditDTO.from(rslt.get());\n\t}\n\n\t@Operation(summary = \"Listado de los actores de la pelicula\")\n\t@ApiResponse(responseCode = \"200\", description = \"Pelicula encontrada\")\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\")\n\t@GetMapping(path = \"/{id}/reparto\")\n\t@Transactional\n\tpublic List<ActorDTO> getFilms(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id)\n\t\t\tthrows Exception {\n\t\tOptional<Film> rslt = srv.getOne(id);\n\t\tif (rslt.isEmpty())\n\t\t\tthrow new NotFoundException();\n\t\treturn rslt.get().getActors().stream().map(item -> ActorDTO.from(item)).toList();\n\t}\n\n\t@Operation(summary = \"Listado de las categorias de la pelicula\")\n\t@ApiResponse(responseCode = \"200\", description = \"Pelicula encontrada\")\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\")\n\t@GetMapping(path = \"/{id}/categorias\")\n\t@Transactional\n\tpublic List<Category> getCategories(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id)\n\t\t\tthrows Exception {\n\t\tOptional<Film> rslt = srv.getOne(id);\n\t\tif (rslt.isEmpty())\n\t\t\tthrow new NotFoundException();\n\t\treturn rslt.get().getCategories();\n\t}\n\n\t@GetMapping(path = \"/clasificaciones\")\n\t@Operation(summary = \"Listado de las clasificaciones por edades\")\n\tpublic List<Map<String, String>> getClasificaciones() {\n\t\treturn List.of(Map.of(\"key\", \"G\", \"value\", \"Todos los públicos\"),\n\t\t\t\tMap.of(\"key\", \"PG\", \"value\", \"Guía paternal sugerida\"),\n\t\t\t\tMap.of(\"key\", \"PG-13\", \"value\", \"Guía paternal estricta\"), \n\t\t\t\tMap.of(\"key\", \"R\", \"value\", \"Restringido\"),\n\t\t\t\tMap.of(\"key\", \"NC-17\", \"value\", \"Prohibido para audiencia de 17 años y menos\"));\n\t}\n\n\t@Operation(summary = \"Añadir una nueva pelicula\")\n\t@ApiResponse(responseCode = \"201\", description = \"Pelicula añadida\")\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\")\n\t@PostMapping\n\t@ResponseStatus(code = HttpStatus.CREATED)\n\t@Transactional\n\tpublic ResponseEntity<Object> add(@RequestBody FilmEditDTO item) throws Exception {\n\t\tFilm newItem = srv.add(FilmEditDTO.from(item));\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(newItem.getFilmId())\n\t\t\t\t.toUri();\n\t\tdeSrv.sendAdd(Film.class.getSimpleName(), newItem.getFilmId());\n\t\treturn ResponseEntity.created(location).build();\n\t}\n\n\t@Operation(summary = \"Modificar una pelicula existente\", description = \"Los identificadores deben coincidir\")\n\t@ApiResponse(responseCode = \"200\", description = \"Pelicula encontrada\")\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\")\n//\t@Transactional\n\t@PutMapping(path = \"/{id}\")\n\tpublic FilmEditDTO modify(\n\t\t\t@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id,\n\t\t\t@Valid @RequestBody FilmEditDTO item) throws Exception {\n\t\tif (item.getFilmId() != id)\n\t\t\tthrow new BadRequestException(\"No coinciden los identificadores\");\n\t\tdeSrv.sendModify(Film.class.getSimpleName(), id);\n\t\treturn FilmEditDTO.from(srv.modify(FilmEditDTO.from(item)));\n\t}\n\n\t@Operation(summary = \"Borrar una pelicula existente\")\n\t@ApiResponse(responseCode = \"204\", description = \"Pelicula borrada\")\n\t@ApiResponse(responseCode = \"404\", description = \"Pelicula no encontrada\")\n\t@DeleteMapping(path = \"/{id}\")\n\t@ResponseStatus(code = HttpStatus.NO_CONTENT)\n\tpublic void delete(@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id)\n\t\t\tthrows Exception {\n\t\tsrv.deleteById(id);\n\t\tdeSrv.sendDelete(Film.class.getSimpleName(), id);\n\t}\n\t\n\t@Autowired\n\tMeGustaProxy proxy;\n\n//\t@Operation(summary = \"Enviar un me gusta\")\n//\t@ApiResponse(responseCode = \"200\", description = \"Like enviado\")\n//\t@PostMapping(path = \"{id}/like\")\n//\tpublic String like(@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id)\n//\t\t\tthrows Exception {\n//\t\treturn proxy.sendLike(id);\n//\t}\n\n\t@PreAuthorize(\"hasRole('ADMINISTRADORES')\")\n\t@Operation(summary = \"Enviar un me gusta\")\n\t@ApiResponse(responseCode = \"200\", description = \"Like enviado\")\n\t@SecurityRequirement(name = \"bearerAuth\")\n\t@PostMapping(path = \"{id}/like\")\n\tpublic String like(@Parameter(description = \"Identificador de la pelicula\", required = true) @PathVariable int id,\n\t\t\t@Parameter(hidden = true) @RequestHeader(required = false) String authorization)\n\t\t\tthrows Exception {\n\t\tif(authorization == null)\n\t\t\treturn proxy.sendLike(id);\n\t\treturn proxy.sendLike(id, authorization);\n\t}\n}" }, { "identifier": "LanguageResource", "path": "REM20231023/catalogo/src/main/java/com/example/application/resources/LanguageResource.java", "snippet": "@RestController\n@RequestMapping(path = \"/idiomas/v1\")\npublic class LanguageResource {\n\t@Autowired\n\tprivate LanguageRepository dao;\n\n\t@GetMapping\n\t@JsonView(Language.Partial.class)\n\tpublic List<Language> getAll() {\n\t\treturn dao.findAll(Sort.by(\"name\"));\n\t}\n\n\t@GetMapping(path = \"/{id}\")\n\t@JsonView(Language.Complete.class)\n\tpublic Language getOne(@PathVariable int id) throws Exception {\n\t\tOptional<Language> rslt = dao.findById(id);\n\t\tif (!rslt.isPresent())\n\t\t\tthrow new NotFoundException();\n\t\treturn rslt.get();\n\t}\n\n\t@GetMapping(path = \"/{id}/peliculas\")\n\t@Transactional\n\tpublic List<FilmShortDTO> getFilms(@PathVariable int id) throws Exception {\n\t\tOptional<Language> rslt = dao.findById(id);\n\t\tif (!rslt.isPresent())\n\t\t\tthrow new NotFoundException();\n\t\treturn rslt.get().getFilms().stream().map(item -> FilmShortDTO.from(item))\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\t@GetMapping(path = \"/{id}/vo\")\n\t@Transactional\n\tpublic List<FilmShortDTO> getFilmsVO(@PathVariable int id) throws Exception {\n\t\tOptional<Language> rslt = dao.findById(id);\n\t\tif (!rslt.isPresent())\n\t\t\tthrow new NotFoundException();\n\t\treturn rslt.get().getFilmsVO().stream().map(item -> FilmShortDTO.from(item))\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\n\t@PostMapping\n\t@ResponseStatus(code = HttpStatus.CREATED)\n\t@JsonView(Language.Partial.class)\n\tpublic ResponseEntity<Object> add(@Valid @RequestBody Language item) throws Exception {\n\t\tif (item.isInvalid())\n\t\t\tthrow new InvalidDataException(item.getErrorsMessage(), item.getErrorsFields());\n\t\tif (dao.findById(item.getLanguageId()).isPresent())\n\t\t\tthrow new InvalidDataException(\"Duplicate key\");\n\t\tdao.save(item);\n\t\tURI location = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\")\n\t\t\t\t.buildAndExpand(item.getLanguageId()).toUri();\n\t\treturn ResponseEntity.created(location).build();\n\t}\n\n\t@PutMapping(path = \"/{id}\")\n\t@JsonView(Language.Partial.class)\n\tpublic Language modify(@PathVariable int id, @Valid @RequestBody Language item) throws Exception {\n\t\tif (item.getLanguageId() != id)\n\t\t\tthrow new BadRequestException(\"No coinciden los ID\");\n\t\tif (item.isInvalid())\n\t\t\tthrow new InvalidDataException(item.getErrorsMessage(), item.getErrorsFields());\n\t\tif (!dao.findById(item.getLanguageId()).isPresent())\n\t\t\tthrow new NotFoundException();\n\t\tdao.save(item);\n\t\treturn item;\n\t}\n\n\t@DeleteMapping(path = \"/{id}\")\n\t@ResponseStatus(code = HttpStatus.NO_CONTENT)\n\t@JsonView(Language.Partial.class)\n\tpublic void delete(@PathVariable int id) throws Exception {\n\t\ttry {\n\t\t\tdao.deleteById(id);\n\t\t} catch (Exception e) {\n\t\t\tthrow new NotFoundException(\"Missing item\", e);\n\t\t}\n\t}\n\n\tpublic List<Language> novedades(Timestamp fecha) {\n\t\treturn dao.findByLastUpdateGreaterThanEqualOrderByLastUpdate(fecha);\n\t}\n\n}" }, { "identifier": "ActorService", "path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/ActorService.java", "snippet": "public interface ActorService extends ProjectionDomainService<Actor, Integer> {\n\tList<Actor> novedades(Timestamp fecha);\n}" }, { "identifier": "CategoryService", "path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/CategoryService.java", "snippet": "public interface CategoryService extends DomainService<Category, Integer> {\n\tList<Category> novedades(Timestamp fecha);\n}" }, { "identifier": "FilmService", "path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/FilmService.java", "snippet": "public interface FilmService extends ProjectionDomainService<Film, Integer> {\n\tList<Film> novedades(Timestamp fecha);\n}" }, { "identifier": "ActorDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/ActorDTO.java", "snippet": "@Value\npublic class ActorDTO {\n\t@JsonProperty(\"id\")\n\tprivate int actorId;\n\t@JsonProperty(\"nombre\")\n\tprivate String firstName;\n\t@JsonProperty(\"apellidos\")\n\tprivate String lastName;\n\t\n\tpublic static ActorDTO from(Actor target) {\n\t\treturn new ActorDTO(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n\tpublic static Actor from(ActorDTO target) {\n\t\treturn new Actor(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n}" }, { "identifier": "FilmEditDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/FilmEditDTO.java", "snippet": "@Schema(name = \"Pelicula (Editar)\", description = \"Version editable de las películas\")\n@Data @AllArgsConstructor @NoArgsConstructor\npublic class FilmEditDTO {\n\t@Schema(description = \"Identificador de la película\", accessMode = AccessMode.READ_ONLY)\n\tprivate int filmId;\n\t@Schema(description = \"Una breve descripción o resumen de la trama de la película\", minLength = 2)\n\tprivate String description;\n\t@Schema(description = \"La duración de la película, en minutos\", minimum = \"0\", exclusiveMinimum = true)\n\tprivate Integer length;\n\t@Schema(description = \"La clasificación por edades asignada a la película\", allowableValues = {\"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\"})\n//\t@Pattern(regexp = \"^(G|PG|PG-13|R|NC-17)$\")\n\tprivate String rating;\n\t@Schema(description = \"El año en que se estrenó la película\", minimum = \"1901\", maximum = \"2155\")\n\tprivate Short releaseYear;\n\t@Schema(description = \"La duración del período de alquiler, en días\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate Byte rentalDuration;\n\t@Schema(description = \"El coste de alquilar la película por el período establecido\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate BigDecimal rentalRate;\n\t@Schema(description = \"El importe cobrado al cliente si la película no se devuelve o se devuelve en un estado dañado\", minimum = \"0\", exclusiveMinimum = true)\n\t@NotNull\n\tprivate BigDecimal replacementCost;\n\t@Schema(description = \"El título de la película\")\n\t@NotBlank\n\t@Size(min=2, max = 128)\n\tprivate String title;\n\t@Schema(description = \"El identificador del idioma de la película\")\n\t@NotNull\n\tprivate Integer languageId;\n\t@Schema(description = \"El identificador del idioma original de la película\")\n\tprivate Integer languageVOId;\n\t@Schema(description = \"La lista de identificadores de actores que participan en la película\")\n\tprivate List<Integer> actors = new ArrayList<Integer>();\n\t@Schema(description = \"La lista de identificadores de categorías asignadas a la película\")\n\t@ArraySchema(uniqueItems = true, minItems = 1, maxItems = 3)\n\tprivate List<Integer> categories = new ArrayList<Integer>();\n\n \tpublic static FilmEditDTO from(Film source) {\n\t\treturn new FilmEditDTO(\n\t\t\t\tsource.getFilmId(), \n\t\t\t\tsource.getDescription(),\n\t\t\t\tsource.getLength(),\n\t\t\t\tsource.getRating() == null ? null : source.getRating().getValue(),\n\t\t\t\tsource.getReleaseYear(),\n\t\t\t\tsource.getRentalDuration(),\n\t\t\t\tsource.getRentalRate(),\n\t\t\t\tsource.getReplacementCost(),\n\t\t\t\tsource.getTitle(),\n\t\t\t\tsource.getLanguage() == null ? null : source.getLanguage().getLanguageId(),\n\t\t\t\tsource.getLanguageVO() == null ? null : source.getLanguageVO().getLanguageId(),\n\t\t\t\tsource.getActors().stream().map(item -> item.getActorId())\n\t\t\t\t\t.collect(Collectors.toList()),\n\t\t\t\tsource.getCategories().stream().map(item -> item.getCategoryId())\n\t\t\t\t\t.collect(Collectors.toList())\n\t\t\t\t);\n\t}\n\tpublic static Film from(FilmEditDTO source) {\n\t\tFilm rslt = new Film(\n\t\t\t\tsource.getFilmId(), \n\t\t\t\tsource.getTitle(),\n\t\t\t\tsource.getDescription(),\n\t\t\t\tsource.getReleaseYear(),\n\t\t\t\tsource.getLanguageId() == null ? null : new Language(source.getLanguageId()),\n\t\t\t\tsource.getLanguageVOId() == null ? null : new Language(source.getLanguageVOId()),\n\t\t\t\tsource.getRentalDuration(),\n\t\t\t\tsource.getRentalRate(),\n\t\t\t\tsource.getLength(),\n\t\t\t\tsource.getReplacementCost(),\n\t\t\t\tsource.getRating() == null ? null : Film.Rating.getEnum(source.getRating())\n\t\t\t\t);\n\t\tsource.getActors().stream().forEach(item -> rslt.addActor(item));\n\t\tsource.getCategories().stream().forEach(item -> rslt.addCategory(item));\n\t\treturn rslt;\n\t}\n\n}" }, { "identifier": "NovedadesDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/NovedadesDTO.java", "snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class NovedadesDTO {\n\tprivate List<FilmEditDTO> films;\n\tprivate List<ActorDTO> actors;\n\tprivate List<Category> categories;\n\tprivate List<Language> languages;\n\t\n}" } ]
import java.sql.Timestamp; import java.time.Instant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.application.resources.FilmResource; import com.example.application.resources.LanguageResource; import com.example.domains.contracts.services.ActorService; import com.example.domains.contracts.services.CategoryService; import com.example.domains.contracts.services.FilmService; import com.example.domains.entities.dtos.ActorDTO; import com.example.domains.entities.dtos.FilmEditDTO; import com.example.domains.entities.dtos.NovedadesDTO;
4,792
package com.example.application.services; @Service public class CatalogoServiceImpl implements CatalogoService { @Autowired private FilmService filmSrv; @Autowired
package com.example.application.services; @Service public class CatalogoServiceImpl implements CatalogoService { @Autowired private FilmService filmSrv; @Autowired
private ActorService artorSrv;
2
2023-10-24 14:35:15+00:00
8k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/web/api/admin/TagsREST.java
[ { "identifier": "ServiceResult", "path": "src/main/java/org/msh/etbm/commons/entities/ServiceResult.java", "snippet": "public class ServiceResult {\n\n private UUID id;\n private String entityName;\n private Class entityClass;\n private Diffs logDiffs;\n private ObjectValues logValues;\n private Operation operation;\n private CommandType commandType;\n private UUID parentId;\n\n public UUID getId() {\n return id;\n }\n\n public void setId(UUID id) {\n this.id = id;\n }\n\n public String getEntityName() {\n return entityName;\n }\n\n public void setEntityName(String name) {\n this.entityName = name;\n }\n\n public Class getEntityClass() {\n return entityClass;\n }\n\n public void setEntityClass(Class entityClass) {\n this.entityClass = entityClass;\n }\n\n public Diffs getLogDiffs() {\n return logDiffs;\n }\n\n public void setLogDiffs(Diffs logDiffs) {\n this.logDiffs = logDiffs;\n }\n\n public ObjectValues getLogValues() {\n return logValues;\n }\n\n public void setLogValues(ObjectValues logValues) {\n this.logValues = logValues;\n }\n\n public Operation getOperation() {\n return operation;\n }\n\n public void setOperation(Operation operation) {\n this.operation = operation;\n }\n\n public CommandType getCommandType() {\n return commandType;\n }\n\n public void setCommandType(CommandType commandType) {\n this.commandType = commandType;\n }\n\n public UUID getParentId() {\n return parentId;\n }\n\n public void setParentId(UUID parentId) {\n this.parentId = parentId;\n }\n}" }, { "identifier": "QueryResult", "path": "src/main/java/org/msh/etbm/commons/entities/query/QueryResult.java", "snippet": "public class QueryResult<E> {\n /**\n * Number of entities found\n */\n private Long count;\n\n /**\n * List of entities returned\n */\n private List<E> list;\n\n public QueryResult(long count, List<E> list) {\n this.count = count;\n this.list = list;\n }\n\n public QueryResult() {\n }\n\n public Long getCount() {\n return count;\n }\n\n public void setCount(Long count) {\n this.count = count;\n }\n\n public List<E> getList() {\n return list;\n }\n\n public void setList(List<E> list) {\n this.list = list;\n }\n}" }, { "identifier": "TagData", "path": "src/main/java/org/msh/etbm/services/admin/tags/TagData.java", "snippet": "public class TagData {\n private UUID id;\n private String name;\n private String sqlCondition;\n private boolean consistencyCheck;\n private boolean active;\n private boolean dailyUpdate;\n private Tag.TagType type;\n\n public UUID getId() {\n return id;\n }\n\n public void setId(UUID id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getSqlCondition() {\n return sqlCondition;\n }\n\n public void setSqlCondition(String sqlCondition) {\n this.sqlCondition = sqlCondition;\n }\n\n public boolean isConsistencyCheck() {\n return consistencyCheck;\n }\n\n public void setConsistencyCheck(boolean consistencyCheck) {\n this.consistencyCheck = consistencyCheck;\n }\n\n public boolean isActive() {\n return active;\n }\n\n public void setActive(boolean active) {\n this.active = active;\n }\n\n public boolean isDailyUpdate() {\n return dailyUpdate;\n }\n\n public void setDailyUpdate(boolean dailyUpdate) {\n this.dailyUpdate = dailyUpdate;\n }\n\n public Tag.TagType getType() {\n return type;\n }\n\n public void setType(Tag.TagType type) {\n this.type = type;\n }\n}" }, { "identifier": "TagFormData", "path": "src/main/java/org/msh/etbm/services/admin/tags/TagFormData.java", "snippet": "public class TagFormData {\n private Optional<String> name;\n private Optional<String> sqlCondition;\n private Optional<Boolean> consistencyCheck;\n private Optional<Boolean> active;\n private Optional<Boolean> dailyUpdate;\n\n public Optional<String> getName() {\n return name;\n }\n\n public void setName(Optional<String> name) {\n this.name = name;\n }\n\n public Optional<String> getSqlCondition() {\n return sqlCondition;\n }\n\n public void setSqlCondition(Optional<String> sqlCondition) {\n this.sqlCondition = sqlCondition;\n }\n\n public Optional<Boolean> getConsistencyCheck() {\n return consistencyCheck;\n }\n\n public void setConsistencyCheck(Optional<Boolean> consistencyCheck) {\n this.consistencyCheck = consistencyCheck;\n }\n\n public Optional<Boolean> getActive() {\n return active;\n }\n\n public void setActive(Optional<Boolean> active) {\n this.active = active;\n }\n\n public Optional<Boolean> getDailyUpdate() {\n return dailyUpdate;\n }\n\n public void setDailyUpdate(Optional<Boolean> dailyUpdate) {\n this.dailyUpdate = dailyUpdate;\n }\n}" }, { "identifier": "TagQueryParams", "path": "src/main/java/org/msh/etbm/services/admin/tags/TagQueryParams.java", "snippet": "public class TagQueryParams extends EntityQueryParams {\n\n public static final String ORDERBY_NAME = \"name\";\n public static final String ORDERBY_TYPE = \"type\";\n\n\n public static final String PROFILE_DEFAULT = \"default\";\n public static final String PROFILE_ITEM = \"item\";\n\n private boolean includeDisabled;\n\n public boolean isIncludeDisabled() {\n return includeDisabled;\n }\n\n public void setIncludeDisabled(boolean includeDisabled) {\n this.includeDisabled = includeDisabled;\n }\n}" }, { "identifier": "TagService", "path": "src/main/java/org/msh/etbm/services/admin/tags/TagService.java", "snippet": "public interface TagService extends EntityService<TagQueryParams> {\n}" }, { "identifier": "Permissions", "path": "src/main/java/org/msh/etbm/services/security/permissions/Permissions.java", "snippet": "@Service\npublic class Permissions {\n\n /**\n * Standard suffix for permissions that are changeable\n */\n private static final String EDIT = \"_EDT\";\n\n /**\n * Administration module permissions\n */\n public static final String ADMIN = \"ADMIN\";\n\n public static final String ADMIN_TABLES = \"TABLES\";\n\n public static final String TABLE_USERS = \"USERS\";\n public static final String TABLE_USERS_EDT = TABLE_USERS + EDIT;\n\n public static final String TABLE_AGERANGES = \"AGERANGES\";\n public static final String TABLE_AGERANGES_EDT = TABLE_AGERANGES + EDIT;\n\n public static final String TABLE_ADMUNITS = \"ADMINUNITS\";\n public static final String TABLE_ADMUNITS_EDT = TABLE_ADMUNITS + EDIT;\n\n public static final String TABLE_SOURCES = \"SOURCES\";\n public static final String TABLE_SOURCES_EDT = TABLE_SOURCES + EDIT;\n\n public static final String TABLE_UNITS = \"UNITS\";\n public static final String TABLE_UNITS_EDT = TABLE_UNITS + EDIT;\n\n public static final String TABLE_PRODUCTS = \"PRODUCTS\";\n public static final String TABLE_PRODUCTS_EDT = TABLE_PRODUCTS + EDIT;\n\n public static final String TABLE_REGIMENS = \"REGIMENS\";\n public static final String TABLE_REGIMENS_EDT = TABLE_REGIMENS + EDIT;\n\n public static final String TABLE_SUBSTANCES = \"SUBSTANCES\";\n public static final String TABLE_SUBSTANCES_EDT = TABLE_SUBSTANCES + EDIT;\n\n public static final String TABLE_TAGS = \"TAGS\";\n public static final String TABLE_TAGS_EDT = TABLE_TAGS + EDIT;\n\n public static final String TABLE_USERPROFILES = \"PROFILES\";\n public static final String TABLE_USERPROFILES_EDT = TABLE_USERPROFILES + EDIT;\n\n public static final String TABLE_WORKSPACES = \"WORKSPACES\";\n public static final String TABLE_WORKSPACES_EDT = TABLE_WORKSPACES + EDIT;\n\n public static final String ADMIN_REPORTS = \"ADMREP\";\n public static final String ADMIN_REP_USERSONLINE = \"ONLINE\";\n public static final String ADMIN_REP_USERSESSIONS = \"USERSESREP\";\n public static final String ADMIN_REP_CMDHISTORY = \"CMDHISTORY\";\n public static final String ADMIN_REP_CMDSTATISTICS = \"CMDSTATISTICS\";\n public static final String ADMIN_REP_ERRORLOG = \"ERRORLOGREP\";\n\n public static final String ADMIN_SETUP_WORKSPACE = \"SETUPWS\";\n public static final String ADMIN_SETUP_SYSTEM = \"SYSSETUP\";\n public static final String ADMIN_CHECKUPDT = \"CHECKUPDT\";\n\n /**\n * Inventory management module permissions\n */\n public static final String INVENTORY = \"INVENTORY\";\n\n public static final String INVENTORY_INIT = \"INVENTORY_INIT\";\n public static final String INV_RECEIV = \"RECEIV\";\n public static final String INV_STOCKADJ = \"STOCK_ADJ\";\n public static final String INV_ORDERS = \"ORDERS\";\n public static final String INV_NEW_ORDER = \"NEW_ORDER\";\n public static final String INV_VAL_ORDER = \"VAL_ORDER\";\n public static final String INV_SEND_ORDER = \"SEND_ORDER\";\n public static final String INV_RECEIV_ORDER = \"RECEIV_ORDER\";\n public static final String INV_ORDER_CANC = \"ORDER_CANC\";\n public static final String INV_DISPENSING = \"DISP_PAC\";\n public static final String INV_TRANSFER = \"TRANSFER\";\n public static final String INV_TRANSF_REC = \"TRANSF_REC\";\n public static final String INV_NEW_TRANSFER = \"NEW_TRANSFER\";\n public static final String INV_TRANSF_CANCEL = \"TRANSF_CANCEL\";\n\n /**\n * Report module permissions\n */\n public static final String REPORTS = \"REPORTS\";\n\n public static final String REP_DATA_ANALYSIS = \"DATA_ANALISYS\";\n public static final String REP_ORDER_LEADTIME = \"REP_ORDER_LEADTIME\";\n public static final String REP_MOVEMENTS = \"REP_MOVEMENTS\";\n\n /**\n * Case management module\n */\n public static final String CASES = \"CASEMAN\";\n\n public static final String CASES_NEWSUSP = \"NEWSUSP\";\n public static final String CASES_NEWCASE = \"NEWCASE\";\n public static final String CASES_TREAT = \"CASE_TREAT\";\n public static final String CASES_INTAKEMED = \"CASE_INTAKEMED\";\n public static final String CASES_EXAM_XPERT = \"EXAM_XPERT\";\n public static final String CASES_EXAM_XPERT_EDT = CASES_EXAM_XPERT + EDIT;\n public static final String CASES_ADDINFO = \"CASE_ADDINFO\";\n public static final String CASES_VALIDATE = \"CASE_VALIDATE\";\n public static final String CASES_DEL_VAL = \"CASE_DEL_VAL\";\n public static final String CASES_TRANSFER = \"CASE_TRANSFER\";\n public static final String CASES_CLOSE = \"CASE_CLOSE\";\n public static final String CASES_REOPEN = \"CASE_REOPEN\";\n public static final String CASES_COMMENTS = \"CASE_COMMENTS\";\n public static final String CASES_REM_COMMENTS = \"REM_COMMENTS\";\n public static final String CASES_TAG = \"CASE_TAG\";\n public static final String CASES_EXAM_CULTURE = \"EXAM_CULTURE\";\n public static final String CASES_EXAM_CULTURE_EDT = CASES_EXAM_CULTURE + EDIT;\n public static final String CASES_EXAM_MICROSCOPY = \"EXAM_MICROSCOPY\";\n public static final String CASES_EXAM_MICROSCOPY_EDT = CASES_EXAM_MICROSCOPY + EDIT;\n public static final String CASES_EXAM_DST = \"EXAM_DST\";\n public static final String CASES_EXAM_DST_EDT = CASES_EXAM_DST + EDIT;\n public static final String CASES_EXAM_XRAY = \"EXAM_XRAY\";\n public static final String CASES_EXAM_XRAY_EDT = CASES_EXAM_XRAY + EDIT;\n public static final String CASES_EXAM_HIV = \"EXAM_HIV\";\n public static final String CASES_EXAM_HIV_EDT = CASES_EXAM_HIV + EDIT;\n public static final String CASES_COMORBIDITIES = \"COMIRBIDITIES\";\n public static final String CASES_COMORBIDITIES_EDT = CASES_COMORBIDITIES + EDIT;\n public static final String CASES_CASE_CONTACT = \"CASECONTACT\";\n public static final String CASES_CASE_CONTACT_EDT = CASES_CASE_CONTACT + EDIT;\n public static final String CASES_ADV_EFFECTS = \"ADV_EFFECTS\";\n public static final String CASES_ADV_EFFECTS_EDT = CASES_ADV_EFFECTS + EDIT;\n public static final String CASES_MED_EXAM = \"CASE_MED_EXAM\";\n public static final String CASES_MED_EXAM_EDT = CASES_MED_EXAM + EDIT;\n public static final String CASES_ISSUES = \"ISSUES\";\n public static final String CASES_NEW_ISSUE = \"NEW_ISSUE\";\n public static final String CASES_ANSWER_ISSUE = \"ANSWER_ISSUE\";\n public static final String CASES_CLOSEDEL_ISSUE = \"CLOSEDEL_ISSUE\";\n\n /**\n * Laboratory module\n */\n public static final String LABS = \"LAB_MODULE\";\n public static final String LABS_NEWREQUEST = \"LAB_NEWREQUEST\";\n public static final String LABS_POSTRESULT = \"LAB_POSTRESULT\";\n public static final String LABS_EDTREQ = \"LAB_EDTREQ\";\n public static final String LABS_REMREQ = \"LAB_REMREQ\";\n\n\n private List<Permission> list;\n\n /**\n * Return the list of permissions in a structured way, i.e, group permissions\n *\n * @return list of group permissions\n */\n public List<Permission> getList() {\n if (list == null) {\n initList();\n }\n return list;\n }\n\n /**\n * Search for a permission by its ID\n *\n * @param id the permission ID\n * @return instance of the permission\n */\n public Permission find(String id) {\n for (Permission perm : getList()) {\n if (perm.getId().equals(id)) {\n return perm;\n }\n Permission aux = perm.find(id);\n if (aux != null) {\n return aux;\n }\n }\n return null;\n }\n\n\n /**\n * Initialize the list of permissions\n */\n private void initList() {\n // define permissions of the cases module\n module(CASES,\n add(CASES_NEWSUSP),\n add(CASES_NEWCASE),\n add(CASES_TREAT, \"cases.details.treatment\"),\n addChangeable(CASES_INTAKEMED),\n addChangeable(CASES_EXAM_MICROSCOPY, \"cases.exammicroscopy\"),\n addChangeable(CASES_EXAM_XPERT, \"cases.examxpert\"),\n addChangeable(CASES_EXAM_CULTURE, \"cases.examculture\"),\n addChangeable(CASES_EXAM_DST, \"cases.examdst\"),\n addChangeable(CASES_EXAM_HIV, \"cases.examhiv\"),\n addChangeable(CASES_EXAM_XRAY, \"cases.examxray\"),\n add(CASES_ADDINFO, \"cases.details.otherinfo\"),\n add(CASES_VALIDATE, \"cases.validate\"),\n add(CASES_DEL_VAL),\n add(CASES_TRANSFER, \"cases.move\"),\n add(CASES_CLOSE, \"cases.close\"),\n add(CASES_REOPEN, \"cases.reopen\"),\n add(CASES_COMMENTS),\n add(CASES_REM_COMMENTS),\n add(CASES_TAG),\n addChangeable(CASES_COMORBIDITIES, \"cases.comorbidities\"),\n addChangeable(CASES_CASE_CONTACT, \"cases.contacts\"),\n addChangeable(CASES_ADV_EFFECTS, \"cases.sideeffects\"),\n addChangeable(CASES_MED_EXAM, \"cases.details.medexam\"),\n add(CASES_ISSUES, \"cases.issues\",\n add(CASES_NEW_ISSUE, \"cases.issues.new\"),\n add(CASES_ANSWER_ISSUE),\n add(CASES_CLOSEDEL_ISSUE)));\n\n module(INVENTORY,\n add(INVENTORY_INIT, \"inventory.start\"),\n add(INV_STOCKADJ, \"inventory.newadjust\"),\n add(INV_RECEIV, \"inventory.receiving\"),\n add(INV_ORDERS, \"inventory.orders\",\n add(INV_NEW_ORDER, \"inventory.orders.new\"),\n add(INV_VAL_ORDER, \"inventory.orders.autorize\"),\n add(INV_SEND_ORDER, \"inventory.orders.shipment\"),\n add(INV_RECEIV_ORDER, \"inventory.orders.receive\"),\n add(INV_ORDER_CANC, \"inventory.orders.cancel\")),\n add(INV_DISPENSING, \"inventory.dispensing\"),\n add(INV_TRANSFER, \"inventory.transfer\",\n add(INV_NEW_TRANSFER, \"inventory.transfer.new\"),\n add(INV_TRANSF_REC, \"inventory.transfer.receive\"),\n add(INV_TRANSF_CANCEL, \"inventory.transfer.cancel\")));\n\n module(LABS,\n add(LABS_NEWREQUEST),\n add(LABS_EDTREQ),\n add(LABS_POSTRESULT),\n add(LABS_REMREQ));\n\n module(REPORTS,\n add(REP_DATA_ANALYSIS, \"reports.dat\"),\n add(REP_MOVEMENTS, \"reports.movements\"),\n add(REP_ORDER_LEADTIME, \"reports.orderleadtime\"));\n\n\n // define permissions of the administration module\n module(ADMIN,\n add(ADMIN_TABLES, \"admin.tables\",\n addChangeable(TABLE_ADMUNITS, \"admin.adminunits\"),\n addChangeable(TABLE_SOURCES, \"admin.sources\"),\n addChangeable(TABLE_UNITS, \"admin.units\"),\n addChangeable(TABLE_SUBSTANCES, \"admin.substances\"),\n addChangeable(TABLE_PRODUCTS, \"admin.products\"),\n addChangeable(TABLE_REGIMENS, \"admin.regimens\"),\n addChangeable(TABLE_AGERANGES, \"admin.ageranges\"),\n addChangeable(TABLE_USERPROFILES, \"admin.profiles\"),\n addChangeable(TABLE_TAGS, \"admin.tags\"),\n addChangeable(TABLE_USERS, \"admin.users\"),\n addChangeable(TABLE_WORKSPACES, \"admin.workspaces\")\n ),\n add(ADMIN_REPORTS, \"admin.reports\",\n add(ADMIN_REP_CMDHISTORY),\n add(ADMIN_REP_CMDSTATISTICS),\n add(ADMIN_REP_USERSONLINE),\n add(ADMIN_REP_USERSESSIONS, \"admin.reports.usersession\"),\n add(ADMIN_REP_ERRORLOG)\n ),\n add(ADMIN_SETUP_WORKSPACE),\n add(ADMIN_SETUP_SYSTEM),\n add(ADMIN_CHECKUPDT)\n );\n\n }\n\n /**\n * Add a root permission, i.e, a module of the system\n *\n * @param id\n * @param children\n * @return\n */\n protected Permission module(String id, Permission... children) {\n if (list == null) {\n list = new ArrayList<>();\n }\n\n Permission perm = add(id, children);\n list.add(perm);\n\n return perm;\n }\n\n private Permission add(String id, Permission... children) {\n return add(id, \"Permission.\" + id, children);\n }\n\n private Permission add(String id, String messageKey, Permission... children) {\n Permission perm = new Permission(null, id, messageKey, false);\n if (children != null && children.length > 0) {\n for (Permission child : children) {\n perm.addPermission(child);\n }\n }\n return perm;\n }\n\n private Permission addChangeable(String id) {\n return new Permission(null, id, \"Permission.\" + id, true);\n }\n\n private Permission addChangeable(String id, String messageKey) {\n return new Permission(null, id, messageKey, true);\n }\n}" }, { "identifier": "StandardResult", "path": "src/main/java/org/msh/etbm/web/api/StandardResult.java", "snippet": "public class StandardResult {\n /**\n * Indicate if the request was succeeded (true) or failed (false)\n */\n private boolean success;\n\n /**\n * The specific result to be sent back (serialized) to the client\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private Object result;\n\n /**\n * The list of error messages, in case validation fails\n */\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private List<Message> errors;\n\n\n public StandardResult() {\n super();\n }\n\n public StandardResult(ServiceResult res) {\n this.success = true;\n this.result = res.getId();\n }\n\n public StandardResult(Object res, List<Message> errors, boolean success) {\n this.result = res;\n this.errors = errors;\n this.success = success;\n }\n\n public boolean isSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public Object getResult() {\n return result;\n }\n\n public void setResult(Object result) {\n this.result = result;\n }\n\n public List<Message> getErrors() {\n return errors;\n }\n\n public void setErrors(List<Message> errors) {\n this.errors = errors;\n }\n\n public static StandardResult createSuccessResult() {\n return new StandardResult(null, null, true);\n }\n}" }, { "identifier": "InstanceType", "path": "src/main/java/org/msh/etbm/web/api/authentication/InstanceType.java", "snippet": "public enum InstanceType {\n SERVER_MODE,\n CLIENT_MODE,\n BOTH\n}" } ]
import org.msh.etbm.commons.entities.ServiceResult; import org.msh.etbm.commons.entities.query.QueryResult; import org.msh.etbm.services.admin.tags.TagData; import org.msh.etbm.services.admin.tags.TagFormData; import org.msh.etbm.services.admin.tags.TagQueryParams; import org.msh.etbm.services.admin.tags.TagService; import org.msh.etbm.services.security.permissions.Permissions; import org.msh.etbm.web.api.StandardResult; import org.msh.etbm.web.api.authentication.Authenticated; import org.msh.etbm.web.api.authentication.InstanceType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.UUID;
5,528
package org.msh.etbm.web.api.admin; /** * Created by rmemoria on 6/1/16. */ @RestController @RequestMapping("/api/tbl") @Authenticated(permissions = {Permissions.TABLE_TAGS_EDT}, instanceType = InstanceType.SERVER_MODE) public class TagsREST { @Autowired TagService service; @RequestMapping(value = "/tag/{id}", method = RequestMethod.GET) public TagData get(@PathVariable UUID id) { return service.findOne(id, TagData.class); } @RequestMapping(value = "/tag", method = RequestMethod.POST)
package org.msh.etbm.web.api.admin; /** * Created by rmemoria on 6/1/16. */ @RestController @RequestMapping("/api/tbl") @Authenticated(permissions = {Permissions.TABLE_TAGS_EDT}, instanceType = InstanceType.SERVER_MODE) public class TagsREST { @Autowired TagService service; @RequestMapping(value = "/tag/{id}", method = RequestMethod.GET) public TagData get(@PathVariable UUID id) { return service.findOne(id, TagData.class); } @RequestMapping(value = "/tag", method = RequestMethod.POST)
public StandardResult create(@Valid @NotNull @RequestBody TagFormData req) {
3
2023-10-23 13:47:54+00:00
8k
exagonsoft/drones-management-board-backend
src/main/java/exagonsoft/drones/service/impl/DroneServiceImpl.java
[ { "identifier": "BatteryLevelDto", "path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}" }, { "identifier": "DroneDto", "path": "src/main/java/exagonsoft/drones/dto/DroneDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DroneDto {\n private Long id;\n private String serial_number;\n private ModelType model;\n private Integer max_weight;\n private Integer battery_capacity;\n private StateType state;\n}" }, { "identifier": "MedicationDto", "path": "src/main/java/exagonsoft/drones/dto/MedicationDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MedicationDto {\n private Long id;\n private String name;\n private Integer weight;\n private String code;\n private String imageUrl;\n}" }, { "identifier": "Drone", "path": "src/main/java/exagonsoft/drones/entity/Drone.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"drones\")\npublic class Drone {\n\n public enum ModelType {\n Lightweight,\n Middleweight,\n Cruiserweight,\n Heavyweight\n }\n\n public enum StateType {\n IDLE,\n LOADING,\n LOADED,\n DELIVERING,\n DELIVERED,\n RETURNING\n }\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"serial_number\", nullable = false, unique = true, length = 100)\n private String serial_number;\n\n @Column(name = \"model\", nullable = false)\n @Enumerated(EnumType.STRING)\n private ModelType model;\n\n @Column(name = \"max_weight\", nullable = false)\n @Max(value = 500, message = \"Maximum weight cannot exceed 500gr\")\n private Integer max_weight;\n\n @Column(name = \"battery_capacity\", nullable = false)\n @Max(value = 100, message = \"Battery capacity cannot exceed 100%\")\n private Integer battery_capacity;\n\n @Column(name = \"state\", nullable = false)\n @Enumerated(EnumType.STRING)\n private StateType state;\n}" }, { "identifier": "DroneMedications", "path": "src/main/java/exagonsoft/drones/entity/DroneMedications.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"drone_medications\")\npublic class DroneMedications {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"drone_id\", nullable = false)\n private Long droneId;\n\n @Column(name = \"medication_id\", nullable = false)\n private Long medicationId;\n}" }, { "identifier": "Medication", "path": "src/main/java/exagonsoft/drones/entity/Medication.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"medications\")\npublic class Medication {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Pattern(regexp = \"^[a-zA-Z0-9_-]*$\", message = \"Name can only contain letters, numbers, '-', and '_'\")\n @Size(max = 255, message = \"Name cannot exceed 255 characters\")\n @Column(name = \"name\", nullable = false, length = 255)\n private String name;\n\n @Column(name = \"weight\", nullable = false)\n private Integer weight;\n\n @Pattern(regexp = \"^[A-Z0-9_]*$\", message = \"Code can only contain uppercase letters, numbers, and '_'\")\n @Size(max = 255, message = \"Code cannot exceed 255 characters\")\n @Column(name = \"code\", nullable = false, length = 255)\n private String code;\n\n @Size(max = 1000, message = \"Image URL/path cannot exceed 1000 characters\")\n @Column(name = \"image_url\", nullable = false, length = 1000)\n private String imageUrl;\n}" }, { "identifier": "StateType", "path": "src/main/java/exagonsoft/drones/entity/Drone.java", "snippet": "public enum StateType {\n IDLE,\n LOADING,\n LOADED,\n DELIVERING,\n DELIVERED,\n RETURNING\n}" }, { "identifier": "DuplicateSerialNumberException", "path": "src/main/java/exagonsoft/drones/exception/DuplicateSerialNumberException.java", "snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class DuplicateSerialNumberException extends RuntimeException{\n public DuplicateSerialNumberException(String message){\n super(message);\n }\n\n @Override\n public String getMessage() {\n return super.getMessage();\n }\n}" }, { "identifier": "ResourceNotFoundException", "path": "src/main/java/exagonsoft/drones/exception/ResourceNotFoundException.java", "snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends RuntimeException {\n\n public ResourceNotFoundException(String message) {\n super(message);\n }\n}" }, { "identifier": "DroneMapper", "path": "src/main/java/exagonsoft/drones/mapper/DroneMapper.java", "snippet": "public class DroneMapper {\n public static DroneDto mapToDroneDto(Drone drone) {\n return new DroneDto(\n drone.getId(),\n drone.getSerial_number(),\n drone.getModel(),\n drone.getMax_weight(),\n drone.getBattery_capacity(),\n drone.getState());\n }\n\n public static Drone mapToDrone(DroneDto droneDto) {\n return new Drone(\n droneDto.getId(),\n droneDto.getSerial_number(),\n droneDto.getModel(),\n droneDto.getMax_weight(),\n droneDto.getBattery_capacity(),\n droneDto.getState());\n }\n}" }, { "identifier": "DroneRepository", "path": "src/main/java/exagonsoft/drones/repository/DroneRepository.java", "snippet": "public interface DroneRepository extends JpaRepository<Drone, Long> {\n @Query(value = \"SELECT * FROM drones WHERE battery_capacity >= 25 AND state = 'IDLE'\", nativeQuery = true)\n List<Drone> findAvailableDrones();\n\n @Query(value = \"SELECT serial_number, battery_capacity, id FROM drones\" , nativeQuery = true)\n List<Object[]> getAllDronesBatteryLevel();\n}" }, { "identifier": "DroneMedicationService", "path": "src/main/java/exagonsoft/drones/service/DroneMedicationService.java", "snippet": "public interface DroneMedicationService {\n List<DroneMedications> listAllDroneMedications(Long droneID);\n DroneMedications createDroneMedication(DroneMedications droneMedications);\n\n @Transactional\n void cleanupDroneMedication(Long droneId);\n \n List<Long> listAllMedicationsIdsByDroneId(Long droneId);\n}" }, { "identifier": "DroneService", "path": "src/main/java/exagonsoft/drones/service/DroneService.java", "snippet": "public interface DroneService {\n DroneDto createDrone(DroneDto droneDto);\n\n DroneDto getDroneByID(Long droneID);\n\n List<DroneDto> listAllDrones();\n\n DroneDto updateDrone(Long id, DroneDto updatedDrone);\n\n List<DroneDto> listAvailableDrones();\n\n BatteryLevelDto checkDroneBatteryLevel(Long droneID);\n\n List<MedicationDto> listDroneMedications(Long droneID);\n\n boolean loadDroneMedications(Long droneID, List<Long> medicationsIds);\n}" }, { "identifier": "MedicationService", "path": "src/main/java/exagonsoft/drones/service/MedicationService.java", "snippet": "public interface MedicationService {\n MedicationDto getMedication(Long medicationID);\n\n MedicationDto createMedication(MedicationDto medicationDto);\n\n MedicationDto updateMedication(Long id, MedicationDto medicationDto);\n\n void deleteMedication(Long medicationID);\n\n MedicationDto getMedicationById(Long medicationId);\n\n List<MedicationDto> listAllMedications();\n\n List<Medication> getMedicationsListByIds(List<Long> medicationIds);\n}" }, { "identifier": "UtilFunctions", "path": "src/main/java/exagonsoft/drones/utils/UtilFunctions.java", "snippet": "public class UtilFunctions {\n\n public static void validateDrone(DroneDto drone) {\n\n if (drone.getMax_weight() > 500) {\n throw new MaxWeightExceededException(\"Drone Max Weight Exceeded!. (max = 500gr)\");\n }\n\n if (drone.getSerial_number().length() > 100) {\n throw new MaxSerialNumberCharacters(\"Drone Serial Number Max Length Exceeded!. (max = 100)\");\n }\n }\n\n public static void validateDroneManagement(DroneDto updatedDrone) {\n\n if (updatedDrone.getState() == StateType.LOADING) {\n if (updatedDrone.getBattery_capacity() < 25) {\n throw new LowBatteryException(\n \"Drone battery level most be greater than 25% to start LOADING state!, (actual:\"\n + updatedDrone.getBattery_capacity() + \"%)\");\n }\n }\n }\n\n public static void validateDroneLoad(int droneMaxWeight, List<Medication> medicationList, StateType state) {\n\n int weightToLoad = medicationList.stream()\n .mapToInt(Medication::getWeight)\n .sum();\n\n if (weightToLoad > droneMaxWeight) {\n throw new MaxWeightExceededException(\"Drone Max Weight Exceeded!. (max = \" + droneMaxWeight + \"gr)\");\n }\n\n if (state != StateType.IDLE) {\n throw new DroneInvalidLoadStateException(\"The Drone can be loaded only in IDLE state!\");\n }\n }\n\n public static void validateMedication(MedicationDto medication) {\n String VALID_PATTERN = \"^[a-zA-Z0-9-_]+$\";\n String VALID_CODE_PATTERN = \"^[A-Z_0-9]+$\";\n Pattern pattern = Pattern.compile(VALID_PATTERN);\n Matcher matcher = pattern.matcher(medication.getName());\n Pattern patternCode = Pattern.compile(VALID_CODE_PATTERN);\n Matcher matcherCode = patternCode.matcher(medication.getCode());\n\n if (!matcher.matches()) {\n\n throw new MedicationInvalidNamePatternException(\n \"Medication Name Pattern Invalid!. (allowed only letters, numbers, ‘-‘, ‘_’)\");\n }\n\n if (!matcherCode.matches()) {\n throw new MedicationCodeInvalidPatternException(\n \"Medication Code Pattern Invalid!. (allowed only upper case letters, underscore and numbers)\");\n }\n }\n\n public static Drone updateDroneLifeCycle(Drone drone, List<Medication> medicationList) {\n try {\n if (drone.getState() == StateType.IDLE) {\n drone.setBattery_capacity(100);\n return drone;\n }\n\n int loadedWeight = medicationList.stream()\n .mapToInt(Medication::getWeight)\n .sum();\n int batterySpend = calculateBatterySpend(loadedWeight);\n int newBatteryLevel = drone.getBattery_capacity() - batterySpend;\n drone.setBattery_capacity(newBatteryLevel);\n switch (drone.getState()) {\n case LOADING:\n drone.setState(StateType.LOADED);\n break;\n case LOADED:\n drone.setState(StateType.DELIVERING);\n break;\n case DELIVERING:\n drone.setState(StateType.DELIVERED);\n break;\n case DELIVERED:\n drone.setState(StateType.RETURNING);\n break;\n case RETURNING:\n drone.setState(StateType.IDLE);\n break;\n default:\n break;\n }\n return drone;\n } catch (Exception e) {\n throw e;\n }\n }\n\n private static int calculateBatterySpend(int weightLoaded) {\n int batterySpend = 1;\n\n if (weightLoaded > 0 && weightLoaded <= 20) {\n batterySpend = 3;\n }\n\n if (weightLoaded > 20 && weightLoaded <= 50) {\n batterySpend = 5;\n }\n\n if (weightLoaded > 50 && weightLoaded <= 150) {\n batterySpend = 6;\n }\n\n if (weightLoaded > 150 && weightLoaded <= 400) {\n batterySpend = 7;\n }\n\n if (weightLoaded > 400) {\n batterySpend = 10;\n }\n\n return batterySpend;\n }\n\n public static void printInfo(String header, String message) {\n try {\n System.out.println(\"\\n\");\n System.out.println(\"****************************\" + header + \"****************************\" + \"\\n\");\n System.out.println(message);\n System.out.println(\"****************************\" + header + \" END ****************************\");\n System.out.println(\"\\n\");\n } catch (Exception e) {\n throw e;\n }\n }\n}" } ]
import java.util.List; import java.util.stream.Collectors; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import exagonsoft.drones.dto.BatteryLevelDto; import exagonsoft.drones.dto.DroneDto; import exagonsoft.drones.dto.MedicationDto; import exagonsoft.drones.entity.Drone; import exagonsoft.drones.entity.DroneMedications; import exagonsoft.drones.entity.Medication; import exagonsoft.drones.entity.Drone.StateType; import exagonsoft.drones.exception.DuplicateSerialNumberException; import exagonsoft.drones.exception.ResourceNotFoundException; import exagonsoft.drones.mapper.DroneMapper; import exagonsoft.drones.repository.DroneRepository; import exagonsoft.drones.service.DroneMedicationService; import exagonsoft.drones.service.DroneService; import exagonsoft.drones.service.MedicationService; import exagonsoft.drones.utils.UtilFunctions; import lombok.AllArgsConstructor;
3,774
package exagonsoft.drones.service.impl; @Service @AllArgsConstructor public class DroneServiceImpl implements DroneService { private DroneRepository droneRepository; private DroneMedicationService droneMedicationService; private MedicationService medicationService; @Override public DroneDto createDrone(DroneDto droneDto) { try { // *Validate the Drone Data*/ UtilFunctions.validateDrone(droneDto); Drone drone = DroneMapper.mapToDrone(droneDto); Drone savedDrone = droneRepository.save(drone); return DroneMapper.mapToDroneDto(savedDrone); } catch (DataIntegrityViolationException e) { throw new DuplicateSerialNumberException("Serial Number already exists!"); } } @Override public DroneDto getDroneByID(Long droneID) { Drone drone = droneRepository.findById(droneID) .orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneID)); return DroneMapper.mapToDroneDto(drone); } @Override public List<DroneDto> listAllDrones() { try { List<Drone> drones = droneRepository.findAll(); return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone)) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException("Something went wrong!"); } } @Override public DroneDto updateDrone(Long droneId, DroneDto updatedDrone) { try { // *Validate the Drone Data*/ UtilFunctions.validateDrone(updatedDrone); UtilFunctions.validateDroneManagement(updatedDrone); Drone drone = droneRepository.findById(droneId) .orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneId)); drone.setMax_weight(updatedDrone.getMax_weight()); drone.setModel(updatedDrone.getModel()); drone.setBattery_capacity(updatedDrone.getBattery_capacity()); drone.setState(updatedDrone.getState()); Drone updatedDroneObj = droneRepository.save(drone); return DroneMapper.mapToDroneDto(updatedDroneObj); } catch (Exception e) { throw e; } } @Override public List<DroneDto> listAvailableDrones() { try { List<Drone> drones = droneRepository.findAvailableDrones(); return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone)) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException("Something went wrong!"); } } @Override
package exagonsoft.drones.service.impl; @Service @AllArgsConstructor public class DroneServiceImpl implements DroneService { private DroneRepository droneRepository; private DroneMedicationService droneMedicationService; private MedicationService medicationService; @Override public DroneDto createDrone(DroneDto droneDto) { try { // *Validate the Drone Data*/ UtilFunctions.validateDrone(droneDto); Drone drone = DroneMapper.mapToDrone(droneDto); Drone savedDrone = droneRepository.save(drone); return DroneMapper.mapToDroneDto(savedDrone); } catch (DataIntegrityViolationException e) { throw new DuplicateSerialNumberException("Serial Number already exists!"); } } @Override public DroneDto getDroneByID(Long droneID) { Drone drone = droneRepository.findById(droneID) .orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneID)); return DroneMapper.mapToDroneDto(drone); } @Override public List<DroneDto> listAllDrones() { try { List<Drone> drones = droneRepository.findAll(); return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone)) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException("Something went wrong!"); } } @Override public DroneDto updateDrone(Long droneId, DroneDto updatedDrone) { try { // *Validate the Drone Data*/ UtilFunctions.validateDrone(updatedDrone); UtilFunctions.validateDroneManagement(updatedDrone); Drone drone = droneRepository.findById(droneId) .orElseThrow(() -> new ResourceNotFoundException("Drone not found with given id: " + droneId)); drone.setMax_weight(updatedDrone.getMax_weight()); drone.setModel(updatedDrone.getModel()); drone.setBattery_capacity(updatedDrone.getBattery_capacity()); drone.setState(updatedDrone.getState()); Drone updatedDroneObj = droneRepository.save(drone); return DroneMapper.mapToDroneDto(updatedDroneObj); } catch (Exception e) { throw e; } } @Override public List<DroneDto> listAvailableDrones() { try { List<Drone> drones = droneRepository.findAvailableDrones(); return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone)) .collect(Collectors.toList()); } catch (Exception e) { throw new RuntimeException("Something went wrong!"); } } @Override
public BatteryLevelDto checkDroneBatteryLevel(Long droneID) {
0
2023-10-16 08:32:39+00:00
8k
weibocom/rill-flow
rill-flow-service/src/main/java/com/weibo/rill/flow/service/statistic/DAGSubmitChecker.java
[ { "identifier": "TaskException", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/exception/TaskException.java", "snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class TaskException extends RuntimeException {\n private final int errorCode;\n private final String executionId;\n\n public TaskException(final int errorCode, final String errorMsg) {\n super(errorMsg);\n this.errorCode = errorCode;\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(final int errorCode, final String errorMsg, final Throwable cause) {\n super(errorMsg, cause);\n this.errorCode = errorCode;\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(final int errorCode, final Throwable cause) {\n super(cause);\n this.errorCode = errorCode;\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(final BizError bizError, final String errorMsg) {\n super(errorMsg);\n this.errorCode = bizError.getCode();\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(BizError bizError, String executionId, String errorMsg) {\n super(errorMsg);\n this.errorCode = bizError.getCode();\n this.executionId = executionId;\n }\n\n public TaskException(final BizError bizError) {\n super(bizError.getCauseMsg());\n this.errorCode = bizError.getCode();\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(final BizError bizError, final String errorMsg, final Throwable cause) {\n super(errorMsg, cause);\n this.errorCode = bizError.getCode();\n this.executionId = StringUtils.EMPTY;\n }\n\n public TaskException(final BizError bizError, final Throwable cause) {\n super(bizError.getCauseMsg(), cause);\n this.errorCode = bizError.getCode();\n this.executionId = StringUtils.EMPTY;\n }\n\n public int getErrorCode() {\n return errorCode;\n }\n\n public String getExecutionId() {\n return executionId;\n }\n}" }, { "identifier": "ResourceCheckConfig", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/function/ResourceCheckConfig.java", "snippet": "@Builder\n@Getter\n@Setter\n@ToString\n@NoArgsConstructor\npublic class ResourceCheckConfig {\n private CheckType checkType;\n private List<String> keyResources;\n\n @JsonCreator\n public ResourceCheckConfig(@JsonProperty(\"check_type\") CheckType checkType,\n @JsonProperty(\"key_resources\") List<String> keyResources) {\n this.checkType = checkType;\n this.keyResources = keyResources;\n }\n\n @AllArgsConstructor\n public enum CheckType {\n SHORT_BOARD(\"short_board\"),\n LONG_BOARD(\"long_board\"),\n KEY_RESOURCE(\"key_resource\"),\n SKIP(\"skip\");\n\n private final String value;\n\n @JsonCreator\n public CheckType parse(String type) {\n for (CheckType checkType : values()) {\n if (checkType.value.equals(type)) {\n return checkType;\n }\n }\n\n return SKIP;\n }\n\n @JsonValue\n public String getValue() {\n return this.value;\n }\n }\n}" }, { "identifier": "ResourceStatus", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/function/ResourceStatus.java", "snippet": "@Getter\n@Setter\n@Builder\npublic class ResourceStatus {\n private String resourceName;\n private List<String> taskNames;\n private volatile long resourceLimitedTime;\n private volatile long updateTime;\n private volatile Long resourceScore;\n\n public boolean isLimited() {\n return resourceLimitedTime >= System.currentTimeMillis();\n }\n}" }, { "identifier": "BizError", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/model/BizError.java", "snippet": "public enum BizError {\n ERROR_INTERNAL(1, \"internal server error\"),\n ERROR_URI(2, \"incorrect uri\"),\n ERROR_AUTH(4, \"auth failed\"),\n ERROR_UNSUPPORTED(5, \"unsupported\"),\n ERROR_PROCESS_FAIL(6, \"process fail\"),\n ERROR_DEGRADED(7, \"feature degraded\"),\n ERROR_FORBIDDEN(8, \"forbidden\"),\n /**\n * 数据格式错误\n */\n ERROR_DATA_FORMAT(9, \"error data format\"),\n /**\n * 数据不合法\n */\n ERROR_DATA_RESTRICTION(10, \"restriction violation\"),\n ERROR_HYSTRIX(11, \"hystrix\"),\n ERROR_MISSING_PARAMETER(12, \"missing parameter args\"),\n ERROR_INVOKE_URI(13, \"error invoke uri\"),\n\n ERROR_REDIRECT_URL(14, \"error redirect url\"),\n\n ERROR_RUNTIME_STORAGE_USAGE_LIMIT(100, \"dag runtime storage usage limit\"),\n ERROR_RUNTIME_RESOURCE_STATUS_LIMIT(101, \"dag runtime resource status limit\"),\n ;\n\n private static final int BASE_ERROR_CODE = 30100;\n\n private static final BizError[] errors = BizError.values();\n\n private final int code;\n private final String causeMsg;\n\n BizError(final int code, final String causeMsg) {\n this.code = code;\n this.causeMsg = causeMsg;\n }\n\n public static BizError valueOf(int code) {\n int realCode = code - BASE_ERROR_CODE;\n for (BizError error : errors) {\n if (error.code == realCode) {\n return error;\n }\n }\n return BizError.ERROR_INTERNAL;\n }\n\n public static JSONObject toJson(BizError bizError) {\n JSONObject errorInfo = new JSONObject();\n errorInfo.put(\"error\", bizError.causeMsg);\n errorInfo.put(\"error_code\", bizError.getCode());\n return errorInfo;\n }\n\n public int getCode() {\n return BASE_ERROR_CODE + code;\n }\n\n public String getCauseMsg() {\n return causeMsg;\n }\n\n}" }, { "identifier": "SerializerUtil", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/util/SerializerUtil.java", "snippet": "public class SerializerUtil {\n private static final ObjectMapper MAPPER = ObjectMapperFactory.getJSONMapper();\n\n public static String serializeToString(Object object) {\n try {\n return MAPPER.writeValueAsString(object);\n } catch (Exception e) {\n throw new TaskException(BizError.ERROR_DATA_FORMAT, e);\n }\n }\n\n public static <T> T deserialize(byte[] bytes, Class<T> type) {\n try {\n return MAPPER.readValue(bytes, type);\n } catch (Exception e) {\n throw new TaskException(BizError.ERROR_DATA_FORMAT, e);\n }\n }\n\n private SerializerUtil() {\n\n }\n}" }, { "identifier": "BeanConfig", "path": "rill-flow-service/src/main/java/com/weibo/rill/flow/service/configuration/BeanConfig.java", "snippet": "@Data\npublic class BeanConfig {\n private Redis redis;\n private Http http;\n private Submit submit;\n\n @Data\n public static class Redis {\n private String master;\n private String slave;\n private String port;\n private Boolean threadIsolation;\n }\n\n @Data\n public static class Http {\n private Integer conTimeOutMs;\n private Integer writeTimeoutMs;\n private Integer readTimeoutMs;\n private Integer maxIdleConnections;\n private Integer keepAliveDurationMs;\n private Integer retryTimes;\n }\n\n @Data\n public static class Submit {\n private Double completeRateThreshold;\n private Double successRateThreshold;\n private Integer heapThreshold;\n }\n}" }, { "identifier": "BizDConfs", "path": "rill-flow-service/src/main/java/com/weibo/rill/flow/service/dconfs/BizDConfs.java", "snippet": "public interface BizDConfs {\n Map<String, ResourceCheckConfig> getResourceCheckIdToConfigBean();\n Map<String,String> getRedisBusinessIdToClientId();\n Map<String,String> getRedisServiceIdToClientId();\n Map<String,Integer> getRedisBusinessIdToFinishReserveSecond();\n Map<String,Integer> getRedisBusinessIdToUnfinishedReserveSecond();\n Map<String,Integer> getRedisBusinessIdToContextMaxLength();\n Map<String,Integer> getRedisBusinessIdToDAGInfoMaxLength();\n Map<String,String> getSwapBusinessIdToClientId();\n Map<String,Integer> getSwapBusinessIdToFinishReserveSecond();\n Map<String,Integer> getSwapBusinessIdToUnfinishedReserveSecond();\n Set<String> getRuntimeRedisUsageCheckIDs();\n Map<String,Integer> getRuntimeRedisStorageIdToMaxUsage();\n int getRuntimeRedisDefaultStorageMaxUsage();\n int getRuntimeRedisCustomizedStorageMaxUsage();\n int getResourceStatusStatisticTimeInSecond();\n Map<String,String> getResourceCheckIdToConfig();\n Map<String,Integer> getSubmitTrafficLimitIdToConfig();\n Set<String> getRuntimeHttpInvokeUrlBlackList();\n int getRuntimeSubmitContextMaxSize();\n int getRuntimeCallbackContextMaxSize();\n Map<String,Integer> getBusinessIdToStatisticLogSaveTimeInMinute();\n Map<String,Integer> getLogStartTimeOffsetInMinute();\n Map<String,Integer> getLogEndTimeOffsetInMinute();\n Set<String> getSysExpFilterIgnoreLogs();\n Map<String, List<String>> getTenantDefinedTaskInvokeProfileLog();\n int getFlowDAGMaxDepth();\n Map<String, String> getLongTermStorageBusinessIdToClientId();\n Map<String, Integer> getLongTermBusinessIdToReserveSecond();\n Map<String, String> getCustomizedBusinessIdToClientId();\n Map<String, String> getCustomizedServiceIdToClientId();\n Map<String, Integer> getCustomizedBusinessIdToReserveSecond();\n Map<String, String> getHttpClientBusinessIdToClientId();\n Map<String, String> getAuthSourceToKeyMap();\n Map<String, String> getTaskScoreExpWhenPop();\n}" }, { "identifier": "DynamicClientConfs", "path": "rill-flow-service/src/main/java/com/weibo/rill/flow/service/dconfs/DynamicClientConfs.java", "snippet": "public interface DynamicClientConfs {\n Map<String, BeanConfig> getRuntimeStorage();\n Map<String, BeanConfig> getLongTermStorage();\n Map<String, BeanConfig> getCustomizedStorage();\n Map<String, BeanConfig> getHttpConfig();\n Map<String, BeanConfig> getSubmitConfig();\n}" }, { "identifier": "SwitcherManager", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/switcher/SwitcherManager.java", "snippet": "public interface SwitcherManager {\n boolean getSwitcherState(String switcher);\n}" }, { "identifier": "ExecutionIdUtil", "path": "rill-flow-service/src/main/java/com/weibo/rill/flow/service/util/ExecutionIdUtil.java", "snippet": "@Slf4j\npublic class ExecutionIdUtil {\n\n /**\n * 格式\n * workspace:dagName_c_suffix\n * 概念\n * businessId: workspace flow中一个业务只能有一个工作空间,即业务与工作空间一一对应,workspace可理解为业务id\n * feature: dagName\n * serviceId: workspace:dagName\n * 文档\n * workspace与dagName说明见Olympicene与flow README文档\n */\n private static final String EXECUTION_ID_FORMAT = \"%s:%s\" + ReservedConstant.EXECUTION_ID_CONNECTOR + \"%s\";\n\n private static final String BUCKET_NAME_PREFIX = \"bucket_\";\n\n public static String generateExecutionId(DAG dag) {\n return String.format(EXECUTION_ID_FORMAT, dag.getWorkspace(), dag.getDagName(), UuidUtil.jobId());\n }\n\n public static String generateExecutionId(String businessId, String featureName) {\n return String.format(EXECUTION_ID_FORMAT, businessId, featureName, UuidUtil.jobId());\n }\n\n public static String generateExecutionId(String serviceId) {\n return serviceId + ReservedConstant.EXECUTION_ID_CONNECTOR + UuidUtil.jobId();\n }\n\n public static String changeExecutionIdToFixedSuffix(String executionId, String suffix) {\n String serviceId = getServiceId(executionId);\n return serviceId + ReservedConstant.EXECUTION_ID_CONNECTOR + suffix;\n }\n\n public static String generateServiceId(DAG dag) {\n return dag.getWorkspace() + \":\" + dag.getDagName();\n }\n\n public static String getBusinessId(String key) {\n int connectorIndex = key.indexOf(ReservedConstant.EXECUTION_ID_CONNECTOR);\n if (connectorIndex < 0) {\n log.info(\"getBusinessId key:{} do not contains executionId\", key);\n return key;\n }\n\n String serviceId = getServiceIdFromExecutionId(key, connectorIndex);\n return getBusinessIdFromServiceId(serviceId);\n }\n\n public static String getBusinessIdFromServiceId(String serviceId) {\n int colonIndex = serviceId.indexOf(ReservedConstant.COLON);\n return colonIndex < 0 ? serviceId : serviceId.substring(0, colonIndex);\n }\n\n public static String getServiceId(String key) {\n int connectorIndex = key.indexOf(ReservedConstant.EXECUTION_ID_CONNECTOR);\n if (connectorIndex < 0) {\n log.info(\"getServiceId key:{} do not contains executionId\", key);\n return key;\n }\n\n return getServiceIdFromExecutionId(key, connectorIndex);\n }\n\n private static String getServiceIdFromExecutionId(String executionId, int connectorIndex) {\n List<Character> specialChar = Lists.newArrayList(':');\n int startIndex = 0;\n for (int index = connectorIndex - 1; index >= 0; index--) {\n char keyChar = executionId.charAt(index);\n if (!CharUtils.isAsciiAlphanumeric(keyChar) && !specialChar.remove((Character) keyChar)) {\n startIndex = index + 1;\n break;\n }\n }\n return executionId.substring(startIndex, connectorIndex);\n }\n\n public static Pair<String, String> getServiceIdAndUUIDFromExecutionId(String executionId) {\n String[] array = executionId.split(ReservedConstant.EXECUTION_ID_CONNECTOR);\n return Pair.of(array[0], array[1]);\n }\n\n public static long getSubmitTime(String executionId) {\n String[] array = executionId.split(ReservedConstant.EXECUTION_ID_CONNECTOR);\n return UuidUtil.timestamp(array[1]);\n }\n\n public static boolean isExecutionId(String source) {\n return StringUtils.isNotEmpty(source)\n && !StringUtils.containsWhitespace(source)\n && source.contains(ReservedConstant.EXECUTION_ID_CONNECTOR);\n }\n\n public static String generateBucketName(String executionId) {\n return BUCKET_NAME_PREFIX + executionId;\n }\n\n public static String getExecutionIdFromBucketName(String bucketName) {\n return bucketName.replaceFirst(BUCKET_NAME_PREFIX, StringUtils.EMPTY);\n }\n\n private ExecutionIdUtil() {\n\n }\n}" } ]
import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.weibo.rill.flow.common.exception.TaskException; import com.weibo.rill.flow.common.function.ResourceCheckConfig; import com.weibo.rill.flow.common.function.ResourceStatus; import com.weibo.rill.flow.common.model.BizError; import com.weibo.rill.flow.common.util.SerializerUtil; import com.weibo.rill.flow.service.configuration.BeanConfig; import com.weibo.rill.flow.service.dconfs.BizDConfs; import com.weibo.rill.flow.service.dconfs.DynamicClientConfs; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.service.util.ExecutionIdUtil; import lombok.Builder; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.RoundingMode; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors;
4,018
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.service.statistic; @Slf4j @Service public class DAGSubmitChecker { @Autowired private BizDConfs bizDConfs; @Autowired private DAGResourceStatistic dagResourceStatistic; @Autowired private TrafficRateLimiter trafficRateLimiter; @Autowired private SystemMonitorStatistic systemMonitorStatistic; @Autowired private DynamicClientConfs dynamicClientConfs; @Autowired private SwitcherManager switcherManagerImpl; public ResourceCheckConfig getCheckConfig(String resourceCheck) { if (StringUtils.isBlank(resourceCheck)) { return null; } try {
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.service.statistic; @Slf4j @Service public class DAGSubmitChecker { @Autowired private BizDConfs bizDConfs; @Autowired private DAGResourceStatistic dagResourceStatistic; @Autowired private TrafficRateLimiter trafficRateLimiter; @Autowired private SystemMonitorStatistic systemMonitorStatistic; @Autowired private DynamicClientConfs dynamicClientConfs; @Autowired private SwitcherManager switcherManagerImpl; public ResourceCheckConfig getCheckConfig(String resourceCheck) { if (StringUtils.isBlank(resourceCheck)) { return null; } try {
return SerializerUtil.deserialize(resourceCheck.getBytes(StandardCharsets.UTF_8), ResourceCheckConfig.class);
4
2023-11-03 03:46:01+00:00
8k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/test/java/org/example/service/impl/ServiceInstanceLifecycleServiceImplTest.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected String code;\n\n /**\n * Response message.\n */\n protected String message;\n\n /**\n * Return data.\n */\n private T data;\n\n protected String requestId;\n\n public static <T> BaseResult<T> success() {\n return new BaseResult<>();\n }\n\n public static <T> BaseResult<T> success(T data) {\n return new BaseResult<>(data);\n }\n\n public static <T> BaseResult<T> fail(String message) {\n return new BaseResult<>(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), message);\n }\n\n public static <T> BaseResult<T> fail(CommonErrorInfo commonErrorInfo) {\n return new BaseResult<>(commonErrorInfo);\n }\n\n public BaseResult() {\n this.code = String.valueOf(HttpStatus.OK.value());\n this.message = HttpStatus.OK.getReasonPhrase();\n this.requestId = MDC.get(REQUEST_ID);\n }\n\n public BaseResult(String code, String message, T data, String requestId) {\n this.code = code;\n this.message = message;\n this.data = data;\n this.requestId = requestId;\n }\n\n public BaseResult(HttpStatus httpStatus) {\n this(String.valueOf(httpStatus.value()), httpStatus.getReasonPhrase());\n }\n\n public BaseResult(CommonErrorInfo commonErrorInfo) {\n this(commonErrorInfo.getCode(), commonErrorInfo.getMessage());\n }\n\n /**\n * If there is no data returned, you can manually specify the status code and message.\n */\n public BaseResult(String code, String msg) {\n this(code,msg,null,MDC.get(REQUEST_ID));\n }\n\n /**\n * When data is returned, the status code is 200, and the default message is \"Operation successful!\"\n */\n public BaseResult(T data) {\n this(HttpStatus.OK.getReasonPhrase(), data);\n }\n\n /**\n * When data is returned, the status code is 200, and the message can be manually specified.\n */\n public BaseResult(String msg, T data) {\n this(String.valueOf(HttpStatus.OK.value()), msg, data, MDC.get(REQUEST_ID));\n }\n\n /**\n * When data is returned, you can customize the status code and manually specify the message.\n */\n public BaseResult(String code, String msg,T data) {\n this(code, msg, data, MDC.get(REQUEST_ID));\n }\n}" }, { "identifier": "ListResult", "path": "boost.common/src/main/java/org/example/common/ListResult.java", "snippet": "public class ListResult<T> extends BaseResult implements Serializable {\n\n private static final long serialVersionUID = 729779190711627058L;\n\n private List<T> data;\n\n private Long count;\n\n private String nextToken;\n\n public ListResult() {\n }\n\n @Override\n public List<T> getData() {\n return this.data;\n }\n\n public void setData(List<T> data) {\n this.data = data;\n }\n\n public Long getCount() {\n return this.count;\n }\n\n public void setCount(long count) {\n this.count = count;\n }\n\n public String getNextToken() {\n return nextToken;\n }\n\n public void setNextToken(String nextToken) {\n this.nextToken = nextToken;\n }\n\n public static <T> ListResult<T> genSuccessListResult(List<T> data, long count) {\n ListResult<T> listResult = new ListResult<T>();\n listResult.setData(data);\n listResult.setCount(count);\n return listResult;\n }\n\n public static <T> ListResult<T> genSuccessListResult(List<T> data, long count, String nextToken) {\n ListResult<T> listResult = new ListResult<T>();\n listResult.setData(data);\n listResult.setCount(count);\n listResult.setNextToken(nextToken);\n return listResult;\n }\n}" }, { "identifier": "ComputeNestSupplierClient", "path": "boost.common/src/main/java/org/example/common/adapter/ComputeNestSupplierClient.java", "snippet": "public interface ComputeNestSupplierClient {\n\n /**\n * List the created instances of the Compute Nest.\n * @param request request\n * @return {@link ListServiceInstancesResponse}\n * @throws Exception exception\n */\n ListServiceInstancesResponse listServiceInstances(ListServiceInstancesRequest request) throws Exception;\n\n /**\n * Get detailed information of a service instance.\n * @param request request\n * @return {@link GetServiceInstanceResponse}\n * @throws Exception exception\n */\n GetServiceInstanceResponse getServiceInstance(GetServiceInstanceRequest request) throws Exception;\n\n /**\n * Create service instance\n * @param request request\n * @return {@link CreateServiceInstanceResponse}\n * @throws Exception bizException\n */\n CreateServiceInstanceResponse createServiceInstance(CreateServiceInstanceRequest request);\n\n /**\n * Continue deploy service instance.\n * @param request request\n * @return {@link ContinueDeployServiceInstanceResponse}\n * @throws Exception exception\n */\n ContinueDeployServiceInstanceResponse continueDeployServiceInstance(ContinueDeployServiceInstanceRequest request);\n\n /**\n * Delete service instance.\n * @param deleteServiceInstancesRequest DeleteServiceInstancesRequest\n * @return DeleteServiceInstancesResponse\n */\n DeleteServiceInstancesResponse deleteServiceInstance(DeleteServiceInstancesRequest deleteServiceInstancesRequest);\n\n /**\n * Create compute nest supplier client by ecs ram role\n * @param aliyunConfig aliyun config\n * @throws Exception Common exception\n */\n void createClient(AliyunConfig aliyunConfig) throws Exception;\n\n /**\n * Create compute nest supplier client by fc header;\n * @param accessKeyId accessKeyId\n * @param accessKeySecret accessKeySecret\n * @param securityToken securityToken\n * @throws Exception Common exception\n */\n void createClient(String accessKeyId, String accessKeySecret, String securityToken) throws Exception;\n\n\n void createClient(String accessKeyId, String accessKeySecret) throws Exception;\n\n /**\n * Get compute nest service info\n * @param request request\n * @return {@link GetServiceResponse}\n */\n GetServiceResponse getService(GetServiceRequest request);\n\n /**\n * Get ROS service template parameter constraints.\n *\n * @param request request\n * @return {@link GetServiceTemplateParameterConstraintsResponse}\n */\n GetServiceTemplateParameterConstraintsResponse getServiceTemplateParameterConstraints(GetServiceTemplateParameterConstraintsRequest request);\n\n /**\n * Update service instance attribute. e.g endTime.\n *\n * @param request request\n * @return {@link GetServiceTemplateParameterConstraintsResponse}\n */\n UpdateServiceInstanceAttributeResponse updateServiceInstanceAttribute(UpdateServiceInstanceAttributeRequest request);\n}" }, { "identifier": "CallSource", "path": "boost.common/src/main/java/org/example/common/constant/CallSource.java", "snippet": "@Getter\npublic enum CallSource {\n\n\n /**\n * 云市场\n */\n Market(2),\n\n /**\n * 计算巢服务商\n */\n Supplier(3),\n\n ;\n private final Integer value;\n\n CallSource(Integer value) {\n this.value = value;\n }\n\n public static CallSource to(Integer value) {\n for (CallSource source : values()) {\n if (source.getValue().equals(value)) {\n return source;\n }\n }\n return null;\n }\n}" }, { "identifier": "ErrorInfo", "path": "boost.common/src/main/java/org/example/common/errorinfo/ErrorInfo.java", "snippet": "public enum ErrorInfo implements CommonErrorInfo {\n SUCCESS(200,\"Success\", \"Success.\"),\n\n RESOURCE_NOT_FOUND(400,\"InvalidParameter\", \"The specified resource or parameter can not be found.\"),\n\n INVALID_INPUT(400, \"InvalidInput\", \"The input parameter(s) is invalid.\"),\n\n VERIFY_FAILED(401,\"UserUnauthorized\",\"User is Unauthorized.\"),\n\n ALIPAY_PAYMENT_FAILED(400, \"PaymentFailed\",\"Payment failed.\"),\n\n SIGNATURE_VERIFICATION_ERROR(400, \"SignatureVerificationError\", \"AliPay Signature Verification Error\"),\n\n ENTITY_NOT_EXIST(400, \"EntityNotExist\",\"The order entity does not exist.\"),\n\n SERVER_UNAVAILABLE(503,\"ServerUnavailable\",\"Server is unavailable.\"),\n\n SPECIFICATION_NOT_EXIST(400, \"SpecificationNotExist\", \"The Specification does not exist.\"),\n\n COLUMN_VALUE_IS_NULL(400, \"Column_Value_Is_Null\", \"The column value can't be null.\"),\n\n CURRENT_ORDER_CANT_BE_DELETED(400, \"Current_Order_Cant_Be_Deleted\", \"The Current Order Cant be deleted.\");\n\n private final int statusCode;\n\n private final String code;\n\n private final String message;\n\n\n @Override\n public int getStatusCode() {\n return statusCode;\n }\n\n ErrorInfo(String code, String message) {\n this(400,code, message);\n }\n\n @Override\n public String getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n ErrorInfo(int statusCode, String code, String message) {\n this.statusCode = statusCode;\n this.code = code;\n this.message = message;\n }\n}" }, { "identifier": "BizException", "path": "boost.common/src/main/java/org/example/common/exception/BizException.java", "snippet": "@Data\npublic class BizException extends RuntimeException {\n\n private static final long serialVersionUID = 5680133981298179266L;\n\n private int statusCode;\n\n private String code;\n\n private String message;\n\n public BizException() {\n super();\n }\n\n public BizException(CommonErrorInfo commonErrorInfo) {\n super(commonErrorInfo.getCode());\n this.statusCode = commonErrorInfo.getStatusCode();\n this.code = commonErrorInfo.getCode();\n this.message = commonErrorInfo.getMessage();\n }\n\n public BizException(CommonErrorInfo commonErrorInfo, Throwable cause) {\n super(commonErrorInfo.getCode(), cause);\n this.statusCode = commonErrorInfo.getStatusCode();\n this.code = commonErrorInfo.getCode();\n this.message = commonErrorInfo.getMessage();\n }\n\n public BizException(int statusCode, String code, String message) {\n super(code);\n this.statusCode = statusCode;\n this.code = code;\n this.message = message;\n }\n\n public BizException(int statusCode, String code, String message, Throwable cause) {\n super(code, cause);\n this.statusCode = statusCode;\n this.code = code;\n this.message = message;\n }\n\n @Override\n public Throwable fillInStackTrace() {\n return this;\n }\n}" }, { "identifier": "ServiceInstanceLifeStyleHelper", "path": "boost.common/src/main/java/org/example/common/helper/ServiceInstanceLifeStyleHelper.java", "snippet": "@Component\npublic class ServiceInstanceLifeStyleHelper {\n\n public Boolean checkServiceInstanceExpiration(List<OrderDTO> orderDtoList, Long currentLocalDateTimeMillis) {\n if (orderDtoList != null && !orderDtoList.isEmpty()) {\n OrderDTO orderDTO = orderDtoList.get(orderDtoList.size() - 1);\n if (orderDTO != null && orderDTO.getBillingEndDateMillis() != null) {\n return currentLocalDateTimeMillis >= orderDTO.getBillingEndDateMillis();\n }\n }\n return Boolean.FALSE;\n }\n\n public ListServiceInstancesRequestFilter createFilter(String key, List<String> values) {\n return new ListServiceInstancesRequestFilter()\n .setName(key)\n .setValue(values);\n }\n}" }, { "identifier": "ListServiceInstancesModel", "path": "boost.common/src/main/java/org/example/common/model/ListServiceInstancesModel.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ListServiceInstancesModel {\n\n private List<ServiceInstanceModel> serviceInstanceModels;\n\n public Integer totalCount;\n\n private String nextToken;\n\n public Integer maxResults;\n}" }, { "identifier": "ServiceInstanceModel", "path": "boost.common/src/main/java/org/example/common/model/ServiceInstanceModel.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ServiceInstanceModel {\n\n private String serviceInstanceId;\n\n private String serviceInstanceName;\n\n private String createTime;\n\n private String updateTime;\n\n private String status;\n\n private Long progress;\n\n private String serviceName;\n\n private ServiceModel serviceModel;\n\n private String parameters;\n\n private String outputs;\n\n private String resources;\n\n private CallSource source;\n}" }, { "identifier": "UserInfoModel", "path": "boost.common/src/main/java/org/example/common/model/UserInfoModel.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserInfoModel {\n\n @JsonProperty(\"sub\")\n private String sub;\n\n @JsonProperty(\"name\")\n private String name;\n\n @JsonProperty(\"login_name\")\n @ApiModelProperty(\"login_name\")\n private String loginName;\n\n @JsonProperty(\"aid\")\n private String aid;\n\n @JsonProperty(\"uid\")\n private String uid;\n}" }, { "identifier": "GetServiceInstanceParam", "path": "boost.common/src/main/java/org/example/common/param/GetServiceInstanceParam.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetServiceInstanceParam {\n\n private String serviceInstanceId;\n}" }, { "identifier": "ListServiceInstancesParam", "path": "boost.common/src/main/java/org/example/common/param/ListServiceInstancesParam.java", "snippet": "@Data\npublic class ListServiceInstancesParam {\n\n private Integer maxResults;\n\n private String nextToken;\n\n private String serviceInstanceId;\n\n private String serviceInstanceName;\n\n private String status;\n}" } ]
import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceRequest; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceRequest; import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceResponse; import com.aliyun.computenestsupplier20210521.models.GetServiceInstanceResponseBody; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesRequest; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesRequest.ListServiceInstancesRequestFilter; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponse; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstances; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstancesService; import com.aliyun.computenestsupplier20210521.models.ListServiceInstancesResponseBody.ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos; import mockit.Expectations; import mockit.Injectable; import mockit.Tested; import mockit.Verifications; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.adapter.ComputeNestSupplierClient; import org.example.common.constant.CallSource; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.model.ListServiceInstancesModel; import org.example.common.model.ServiceInstanceModel; import org.example.common.model.UserInfoModel; import org.example.common.param.GetServiceInstanceParam; import org.example.common.param.ListServiceInstancesParam; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals;
4,313
/* *Copyright (c) Alibaba Group; *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.example.service.impl; class ServiceInstanceLifecycleServiceImplTest { @Tested private ServiceInstanceLifecycleServiceImpl serviceInstanceLifecycleService; @Injectable private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Injectable private ComputeNestSupplierClient computeNestSupplierClient; private ListServiceInstancesResponseBody createListServiceInstancesResponseBody() { ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos serviceInfos = new ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos().setName("serviceInfoName-2").setShortDescription("description"); ListServiceInstancesResponseBodyServiceInstancesService service = new ListServiceInstancesResponseBodyServiceInstancesService().setServiceInfos(Arrays.asList(serviceInfos)); ListServiceInstancesResponseBodyServiceInstances deployedServiceInstance = new ListServiceInstancesResponseBodyServiceInstances().setServiceInstanceId("si-serviceInstanceId-1") .setStatus("deployed").setService(service); ListServiceInstancesResponseBody responseBody = new ListServiceInstancesResponseBody().setMaxResults(20) .setServiceInstances(Arrays.asList(deployedServiceInstance, deployedServiceInstance)); responseBody.setTotalCount(2); return responseBody; } @Test void listServiceInstances() throws Exception { UserInfoModel userInfoModel = new UserInfoModel(); userInfoModel.setAid("aliYunId"); ListServiceInstancesParam listServiceInstancesParam = new ListServiceInstancesParam(); listServiceInstancesParam.setMaxResults(20); listServiceInstancesParam.setStatus("deployed"); listServiceInstancesParam.setServiceInstanceId("si-serviceInstanceId"); listServiceInstancesParam.setServiceInstanceName("serviceInfoName-2"); ListServiceInstancesRequestFilter listServiceInstancesRequestFilter = new ListServiceInstancesRequestFilter(); listServiceInstancesRequestFilter.setName("ServiceType"); List<String> list = new ArrayList<>(); list.add("managed"); listServiceInstancesRequestFilter.setValue(list); new Expectations() {{ serviceInstanceLifeStyleHelper.createFilter(anyString, withAny(new ArrayList<>())); result = listServiceInstancesRequestFilter; ListServiceInstancesResponse response = new ListServiceInstancesResponse(); response.setBody(createListServiceInstancesResponseBody()); computeNestSupplierClient.listServiceInstances(withAny(new ListServiceInstancesRequest())); result = response; }};
/* *Copyright (c) Alibaba Group; *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.example.service.impl; class ServiceInstanceLifecycleServiceImplTest { @Tested private ServiceInstanceLifecycleServiceImpl serviceInstanceLifecycleService; @Injectable private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Injectable private ComputeNestSupplierClient computeNestSupplierClient; private ListServiceInstancesResponseBody createListServiceInstancesResponseBody() { ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos serviceInfos = new ListServiceInstancesResponseBodyServiceInstancesServiceServiceInfos().setName("serviceInfoName-2").setShortDescription("description"); ListServiceInstancesResponseBodyServiceInstancesService service = new ListServiceInstancesResponseBodyServiceInstancesService().setServiceInfos(Arrays.asList(serviceInfos)); ListServiceInstancesResponseBodyServiceInstances deployedServiceInstance = new ListServiceInstancesResponseBodyServiceInstances().setServiceInstanceId("si-serviceInstanceId-1") .setStatus("deployed").setService(service); ListServiceInstancesResponseBody responseBody = new ListServiceInstancesResponseBody().setMaxResults(20) .setServiceInstances(Arrays.asList(deployedServiceInstance, deployedServiceInstance)); responseBody.setTotalCount(2); return responseBody; } @Test void listServiceInstances() throws Exception { UserInfoModel userInfoModel = new UserInfoModel(); userInfoModel.setAid("aliYunId"); ListServiceInstancesParam listServiceInstancesParam = new ListServiceInstancesParam(); listServiceInstancesParam.setMaxResults(20); listServiceInstancesParam.setStatus("deployed"); listServiceInstancesParam.setServiceInstanceId("si-serviceInstanceId"); listServiceInstancesParam.setServiceInstanceName("serviceInfoName-2"); ListServiceInstancesRequestFilter listServiceInstancesRequestFilter = new ListServiceInstancesRequestFilter(); listServiceInstancesRequestFilter.setName("ServiceType"); List<String> list = new ArrayList<>(); list.add("managed"); listServiceInstancesRequestFilter.setValue(list); new Expectations() {{ serviceInstanceLifeStyleHelper.createFilter(anyString, withAny(new ArrayList<>())); result = listServiceInstancesRequestFilter; ListServiceInstancesResponse response = new ListServiceInstancesResponse(); response.setBody(createListServiceInstancesResponseBody()); computeNestSupplierClient.listServiceInstances(withAny(new ListServiceInstancesRequest())); result = response; }};
ListResult<ServiceInstanceModel> result = serviceInstanceLifecycleService.listServiceInstances(userInfoModel, listServiceInstancesParam);
1
2023-11-01 08:19:34+00:00
8k
mioclient/oyvey-ported
src/main/java/me/alpha432/oyvey/manager/ModuleManager.java
[ { "identifier": "Render2DEvent", "path": "src/main/java/me/alpha432/oyvey/event/impl/Render2DEvent.java", "snippet": "public class Render2DEvent extends Event {\n private final DrawContext context;\n private final float delta;\n\n public Render2DEvent(DrawContext context, float delta) {\n this.context = context;\n this.delta = delta;\n }\n\n public DrawContext getContext() {\n return context;\n }\n\n public float getDelta() {\n return delta;\n }\n}" }, { "identifier": "Render3DEvent", "path": "src/main/java/me/alpha432/oyvey/event/impl/Render3DEvent.java", "snippet": "public class Render3DEvent extends Event {\n private final MatrixStack matrix;\n private final float delta;\n\n public Render3DEvent(MatrixStack matrix, float delta) {\n this.matrix = matrix;\n this.delta = delta;\n }\n\n public MatrixStack getMatrix() {\n return matrix;\n }\n\n public float getDelta() {\n return delta;\n }\n}" }, { "identifier": "Feature", "path": "src/main/java/me/alpha432/oyvey/features/Feature.java", "snippet": "public class Feature\n implements Util {\n public List<Setting<?>> settings = new ArrayList<>();\n private String name;\n\n public Feature() {\n }\n\n public Feature(String name) {\n this.name = name;\n }\n\n public static boolean nullCheck() {\n return Feature.mc.player == null;\n }\n\n public static boolean fullNullCheck() {\n return Feature.mc.player == null || Feature.mc.world == null;\n }\n\n public String getName() {\n return this.name;\n }\n\n public List<Setting<?>> getSettings() {\n return this.settings;\n }\n\n public boolean hasSettings() {\n return !this.settings.isEmpty();\n }\n\n public boolean isEnabled() {\n return false;\n }\n\n public boolean isDisabled() {\n return !this.isEnabled();\n }\n\n public <T> Setting<T> register(Setting<T> setting) {\n setting.setFeature(this);\n this.settings.add(setting);\n// if (this instanceof Module && Feature.mc.currentScreen instanceof OyVeyGui) {\n// OyVeyGui.getInstance().updateModule((Module) this);\n// }\n return setting;\n }\n\n public void unregister(Setting<?> settingIn) {\n ArrayList<Setting<?>> removeList = new ArrayList<>();\n for (Setting<?> setting : this.settings) {\n if (!setting.equals(settingIn)) continue;\n removeList.add(setting);\n }\n if (!removeList.isEmpty()) {\n this.settings.removeAll(removeList);\n }\n// if (this instanceof Module && Feature.mc.currentScreen instanceof OyVeyGui) {\n// OyVeyGui.getInstance().updateModule((Module) this);\n// }\n }\n\n public Setting<?> getSettingByName(String name) {\n for (Setting<?> setting : this.settings) {\n if (!setting.getName().equalsIgnoreCase(name)) continue;\n return setting;\n }\n return null;\n }\n\n public void reset() {\n for (Setting<?> setting : this.settings) {\n setting.reset();\n }\n }\n\n public void clearSettings() {\n this.settings = new ArrayList<>();\n }\n}" }, { "identifier": "Module", "path": "src/main/java/me/alpha432/oyvey/features/modules/Module.java", "snippet": "public class Module extends Feature implements Jsonable {\n private final String description;\n private final Category category;\n public Setting<Boolean> enabled = this.register(new Setting<>(\"Enabled\", false));\n public Setting<Boolean> drawn = this.register(new Setting<>(\"Drawn\", true));\n public Setting<Bind> bind = this.register(new Setting<>(\"Keybind\", new Bind(-1)));\n public Setting<String> displayName;\n public boolean hasListener;\n public boolean alwaysListening;\n public boolean hidden;\n\n public Module(String name, String description, Category category, boolean hasListener, boolean hidden, boolean alwaysListening) {\n super(name);\n this.displayName = this.register(new Setting<>(\"DisplayName\", name));\n this.description = description;\n this.category = category;\n this.hasListener = hasListener;\n this.hidden = hidden;\n this.alwaysListening = alwaysListening;\n }\n\n public void onEnable() {\n }\n\n public void onDisable() {\n }\n\n public void onToggle() {\n }\n\n public void onLoad() {\n }\n\n public void onTick() {\n }\n\n public void onUpdate() {\n }\n\n public void onRender2D(Render2DEvent event) {\n }\n\n public void onRender3D(Render3DEvent event) {\n }\n\n public void onUnload() {\n }\n\n public String getDisplayInfo() {\n return null;\n }\n\n public boolean isOn() {\n return this.enabled.getValue();\n }\n\n public boolean isOff() {\n return !this.enabled.getValue();\n }\n\n public void setEnabled(boolean enabled) {\n if (enabled) {\n this.enable();\n } else {\n this.disable();\n }\n }\n\n public void enable() {\n this.enabled.setValue(true);\n this.onToggle();\n this.onEnable();\n if (this.isOn() && this.hasListener && !this.alwaysListening) {\n EVENT_BUS.register(this);\n }\n }\n\n public void disable() {\n if (this.hasListener && !this.alwaysListening) {\n EVENT_BUS.unregister(this);\n }\n this.enabled.setValue(false);\n this.onToggle();\n this.onDisable();\n }\n\n public void toggle() {\n ClientEvent event = new ClientEvent(!this.isEnabled() ? 1 : 0, this);\n EVENT_BUS.post(event);\n if (!event.isCancelled()) {\n this.setEnabled(!this.isEnabled());\n }\n }\n\n public String getDisplayName() {\n return this.displayName.getValue();\n }\n\n public void setDisplayName(String name) {\n Module module = OyVey.moduleManager.getModuleByDisplayName(name);\n Module originalModule = OyVey.moduleManager.getModuleByName(name);\n if (module == null && originalModule == null) {\n Command.sendMessage(this.getDisplayName() + \", name: \" + this.getName() + \", has been renamed to: \" + name);\n this.displayName.setValue(name);\n return;\n }\n Command.sendMessage(Formatting.RED + \"A module of this name already exists.\");\n }\n\n @Override public boolean isEnabled() {\n return isOn();\n }\n\n public String getDescription() {\n return this.description;\n }\n\n public boolean isDrawn() {\n return this.drawn.getValue();\n }\n\n public void setDrawn(boolean drawn) {\n this.drawn.setValue(drawn);\n }\n\n public Category getCategory() {\n return this.category;\n }\n\n public String getInfo() {\n return null;\n }\n\n public Bind getBind() {\n return this.bind.getValue();\n }\n\n public void setBind(int key) {\n this.bind.setValue(new Bind(key));\n }\n\n public boolean listening() {\n return this.hasListener && this.isOn() || this.alwaysListening;\n }\n\n public String getFullArrayString() {\n return this.getDisplayName() + Formatting.GRAY + (this.getDisplayInfo() != null ? \" [\" + Formatting.WHITE + this.getDisplayInfo() + Formatting.GRAY + \"]\" : \"\");\n }\n\n @Override public JsonElement toJson() {\n JsonObject object = new JsonObject();\n for (Setting<?> setting : getSettings()) {\n try {\n if (setting.getValue() instanceof Bind bind) {\n object.addProperty(setting.getName(), bind.getKey());\n } else {\n object.addProperty(setting.getName(), setting.getValueAsString());\n }\n } catch (Throwable e) {\n }\n }\n return object;\n }\n\n @Override public void fromJson(JsonElement element) {\n JsonObject object = element.getAsJsonObject();\n String enabled = object.get(\"Enabled\").getAsString();\n if (Boolean.parseBoolean(enabled)) toggle();\n for (Setting<?> setting : getSettings()) {\n try {\n ConfigManager.setValueFromJson(this, setting, object.get(setting.getName()));\n } catch (Throwable throwable) {\n }\n }\n }\n\n public enum Category {\n COMBAT(\"Combat\"),\n MISC(\"Misc\"),\n RENDER(\"Render\"),\n MOVEMENT(\"Movement\"),\n PLAYER(\"Player\"),\n CLIENT(\"Client\");\n\n private final String name;\n\n Category(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n }\n}" }, { "identifier": "ClickGui", "path": "src/main/java/me/alpha432/oyvey/features/modules/client/ClickGui.java", "snippet": "public class ClickGui\n extends Module {\n private static ClickGui INSTANCE = new ClickGui();\n public Setting<String> prefix = this.register(new Setting<>(\"Prefix\", \".\"));\n public Setting<Boolean> customFov = this.register(new Setting<>(\"CustomFov\", false));\n public Setting<Float> fov = this.register(new Setting<>(\"Fov\", 150f, -180f, 180f));\n public Setting<Integer> red = this.register(new Setting<>(\"Red\", 0, 0, 255));\n public Setting<Integer> green = this.register(new Setting<>(\"Green\", 0, 0, 255));\n public Setting<Integer> blue = this.register(new Setting<>(\"Blue\", 255, 0, 255));\n public Setting<Integer> hoverAlpha = this.register(new Setting<>(\"Alpha\", 180, 0, 255));\n public Setting<Integer> topRed = this.register(new Setting<>(\"SecondRed\", 0, 0, 255));\n public Setting<Integer> topGreen = this.register(new Setting<>(\"SecondGreen\", 0, 0, 255));\n public Setting<Integer> topBlue = this.register(new Setting<>(\"SecondBlue\", 150, 0, 255));\n public Setting<Integer> alpha = this.register(new Setting<>(\"HoverAlpha\", 240, 0, 255));\n public Setting<Boolean> rainbow = this.register(new Setting<>(\"Rainbow\", false));\n public Setting<rainbowMode> rainbowModeHud = this.register(new Setting<>(\"HRainbowMode\", rainbowMode.Static, v -> this.rainbow.getValue()));\n public Setting<rainbowModeArray> rainbowModeA = this.register(new Setting<>(\"ARainbowMode\", rainbowModeArray.Static, v -> this.rainbow.getValue()));\n public Setting<Integer> rainbowHue = this.register(new Setting<>(\"Delay\", 240, 0, 600, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowBrightness = this.register(new Setting<>(\"Brightness \", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n public Setting<Float> rainbowSaturation = this.register(new Setting<>(\"Saturation\", 150.0f, 1.0f, 255.0f, v -> this.rainbow.getValue()));\n private OyVeyGui click;\n\n public ClickGui() {\n super(\"ClickGui\", \"Opens the ClickGui\", Module.Category.CLIENT, true, false, false);\n setBind(GLFW.GLFW_KEY_RIGHT_SHIFT);\n this.setInstance();\n }\n\n public static ClickGui getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new ClickGui();\n }\n return INSTANCE;\n }\n\n private void setInstance() {\n INSTANCE = this;\n }\n\n @Override\n public void onUpdate() {\n if (this.customFov.getValue().booleanValue()) {\n mc.options.getFov().setValue(this.fov.getValue().intValue());\n }\n }\n\n @Subscribe\n public void onSettingChange(ClientEvent event) {\n if (event.getStage() == 2 && event.getSetting().getFeature().equals(this)) {\n if (event.getSetting().equals(this.prefix)) {\n OyVey.commandManager.setPrefix(this.prefix.getPlannedValue());\n Command.sendMessage(\"Prefix set to \" + Formatting.DARK_GRAY + OyVey.commandManager.getPrefix());\n }\n OyVey.colorManager.setColor(this.red.getPlannedValue(), this.green.getPlannedValue(), this.blue.getPlannedValue(), this.hoverAlpha.getPlannedValue());\n }\n }\n\n @Override\n public void onEnable() {\n mc.setScreen(OyVeyGui.getClickGui());\n }\n\n @Override\n public void onLoad() {\n OyVey.colorManager.setColor(this.red.getValue(), this.green.getValue(), this.blue.getValue(), this.hoverAlpha.getValue());\n OyVey.commandManager.setPrefix(this.prefix.getValue());\n }\n\n @Override\n public void onTick() {\n if (!(ClickGui.mc.currentScreen instanceof OyVeyGui)) {\n this.disable();\n }\n }\n\n public enum rainbowModeArray {\n Static,\n Up\n\n }\n\n public enum rainbowMode {\n Static,\n Sideway\n\n }\n}" }, { "identifier": "HudModule", "path": "src/main/java/me/alpha432/oyvey/features/modules/client/HudModule.java", "snippet": "public class HudModule extends Module {\n public HudModule() {\n super(\"Hud\", \"hud\", Category.CLIENT, true, false, false);\n }\n\n @Override public void onRender2D(Render2DEvent event) {\n event.getContext().drawTextWithShadow(\n mc.textRenderer,\n OyVey.NAME + \" \" + OyVey.VERSION,\n 2, 2,\n -1\n );\n }\n}" }, { "identifier": "Criticals", "path": "src/main/java/me/alpha432/oyvey/features/modules/combat/Criticals.java", "snippet": "public class Criticals extends Module {\n private final Timer timer = new Timer();\n public Criticals() {\n super(\"Criticals\", \"\", Category.COMBAT, true, false, false);\n }\n @Subscribe private void onPacketSend(PacketEvent.Send event) {\n if (event.getPacket() instanceof PlayerInteractEntityC2SPacket packet && packet.type.getType() == PlayerInteractEntityC2SPacket.InteractType.ATTACK) {\n Entity entity = mc.world.getEntityById(packet.entityId);\n if (entity == null\n || entity instanceof EndCrystalEntity\n || !mc.player.isOnGround()\n || !(entity instanceof LivingEntity)\n || !timer.passedMs(0)) return;\n\n mc.player.networkHandler.sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY() + (double) 0.1f, mc.player.getZ(), false));\n mc.player.networkHandler.sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), false));\n mc.player.addCritParticles(entity);\n timer.reset();\n }\n }\n\n @Override public String getDisplayInfo() {\n return \"Packet\";\n }\n}" }, { "identifier": "MCF", "path": "src/main/java/me/alpha432/oyvey/features/modules/misc/MCF.java", "snippet": "public class MCF extends Module {\n private boolean pressed;\n public MCF() {\n super(\"MCF\", \"\", Category.MISC, true, false, false);\n }\n\n @Override public void onTick() {\n if (GLFW.glfwGetMouseButton(mc.getWindow().getHandle(), 2) == 1) {\n if (!pressed) {\n Entity targetedEntity = mc.targetedEntity;\n if (!(targetedEntity instanceof PlayerEntity)) return;\n String name = ((PlayerEntity) targetedEntity).getGameProfile().getName();\n\n if (OyVey.friendManager.isFriend(name)) {\n OyVey.friendManager.removeFriend(name);\n Command.sendMessage(Formatting.RED + name + Formatting.RED + \" has been unfriended.\");\n } else {\n OyVey.friendManager.addFriend(name);\n Command.sendMessage(Formatting.AQUA + name + Formatting.AQUA + \" has been friended.\");\n }\n\n pressed = true;\n }\n } else {\n pressed = false;\n }\n }\n}" }, { "identifier": "ReverseStep", "path": "src/main/java/me/alpha432/oyvey/features/modules/movement/ReverseStep.java", "snippet": "public class ReverseStep extends Module {\n public ReverseStep() {\n super(\"ReverseStep\", \"step but reversed..\", Category.MOVEMENT, true, false, false);\n }\n\n @Override public void onUpdate() {\n if (nullCheck()) return;\n if (mc.player.isInLava() || mc.player.isTouchingWater() || !mc.player.isOnGround()) return;\n mc.player.addVelocity(0, -1, 0);\n }\n}" }, { "identifier": "Step", "path": "src/main/java/me/alpha432/oyvey/features/modules/movement/Step.java", "snippet": "public class Step extends Module {\n private final Setting<Float> height = register(new Setting<>(\"Height\", 2f, 1f, 3f, v -> true));\n public Step() {\n super(\"Step\", \"step..\", Category.MOVEMENT, true, false, false);\n }\n\n @Override public void onDisable() {\n if (nullCheck()) return;\n mc.player.setStepHeight(0.6f);\n }\n\n @Override public void onUpdate() {\n if (nullCheck()) return;\n mc.player.setStepHeight(height.getValue());\n }\n}" }, { "identifier": "FastPlace", "path": "src/main/java/me/alpha432/oyvey/features/modules/player/FastPlace.java", "snippet": "public class FastPlace extends Module {\n public FastPlace() {\n super(\"FastPlace\", \"\", Category.PLAYER, true, false, false);\n }\n\n @Override public void onUpdate() {\n if (nullCheck()) return;\n\n if (mc.player.isHolding(Items.EXPERIENCE_BOTTLE)) {\n mc.itemUseCooldown = 0;\n }\n }\n}" }, { "identifier": "Velocity", "path": "src/main/java/me/alpha432/oyvey/features/modules/player/Velocity.java", "snippet": "public class Velocity extends Module {\n public Velocity() {\n super(\"Velocity\", \"\", Category.PLAYER, true, false, false);\n }\n\n @Subscribe private void onPacketReceive(PacketEvent.Receive event) {\n if (event.getPacket() instanceof EntityVelocityUpdateS2CPacket || event.getPacket() instanceof ExplosionS2CPacket) event.cancel();\n }\n}" }, { "identifier": "Jsonable", "path": "src/main/java/me/alpha432/oyvey/util/traits/Jsonable.java", "snippet": "public interface Jsonable {\n JsonElement toJson();\n\n void fromJson(JsonElement element);\n\n default String getFileName() {\n return \"\";\n }\n}" }, { "identifier": "Util", "path": "src/main/java/me/alpha432/oyvey/util/traits/Util.java", "snippet": "public interface Util {\n MinecraftClient mc = MinecraftClient.getInstance();\n EventBus EVENT_BUS = new EventBus();\n}" } ]
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import me.alpha432.oyvey.event.impl.Render2DEvent; import me.alpha432.oyvey.event.impl.Render3DEvent; import me.alpha432.oyvey.features.Feature; import me.alpha432.oyvey.features.modules.Module; import me.alpha432.oyvey.features.modules.client.ClickGui; import me.alpha432.oyvey.features.modules.client.HudModule; import me.alpha432.oyvey.features.modules.combat.Criticals; import me.alpha432.oyvey.features.modules.misc.MCF; import me.alpha432.oyvey.features.modules.movement.ReverseStep; import me.alpha432.oyvey.features.modules.movement.Step; import me.alpha432.oyvey.features.modules.player.FastPlace; import me.alpha432.oyvey.features.modules.player.Velocity; import me.alpha432.oyvey.util.traits.Jsonable; import me.alpha432.oyvey.util.traits.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors;
4,762
package me.alpha432.oyvey.manager; public class ModuleManager implements Jsonable, Util { public List<Module> modules = new ArrayList<>(); public List<Module> sortedModules = new ArrayList<>(); public List<String> sortedModulesABC = new ArrayList<>(); public void init() { modules.add(new HudModule()); modules.add(new ClickGui()); modules.add(new Criticals());
package me.alpha432.oyvey.manager; public class ModuleManager implements Jsonable, Util { public List<Module> modules = new ArrayList<>(); public List<Module> sortedModules = new ArrayList<>(); public List<String> sortedModulesABC = new ArrayList<>(); public void init() { modules.add(new HudModule()); modules.add(new ClickGui()); modules.add(new Criticals());
modules.add(new MCF());
7
2023-11-05 18:10:28+00:00
8k
EB-wilson/TooManyItems
src/main/java/tmi/recipe/parser/ThermalGeneratorParser.java
[ { "identifier": "Recipe", "path": "src/main/java/tmi/recipe/Recipe.java", "snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeType;\n /**配方的标准耗时,具体来说即该配方在100%的工作效率下执行一次生产的耗时,任意小于0的数字都被认为生产过程是连续的*/\n //meta\n public float time = -1;\n\n /**配方的产出物列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> productions = new OrderedMap<>();\n /**配方的输入材料列表\n * @see RecipeItemStack*/\n public final OrderedMap<RecipeItem<?>, RecipeItemStack> materials = new OrderedMap<>();\n\n /**配方的效率计算函数,用于给定一个输入环境参数和配方数据,计算出该配方在这个输入环境下的工作效率*/\n public EffFunc efficiency = getOneEff();\n\n //infos\n /**执行该配方的建筑/方块*/\n public RecipeItem<?> block;\n /**该配方在显示时的附加显示内容构建函数,若不设置则认为不添加任何附加信息*/\n @Nullable public Cons<Table> subInfoBuilder;\n\n public Recipe(RecipeType recipeType) {\n this.recipeType = recipeType;\n }\n\n /**用配方当前使用的效率计算器计算该配方在给定的环境参数下的运行效率*/\n public float calculateEfficiency(EnvParameter parameter) {\n return efficiency.calculateEff(this, parameter, calculateMultiple(parameter));\n }\n\n public float calculateEfficiency(EnvParameter parameter, float multiplier) {\n return efficiency.calculateEff(this, parameter, multiplier);\n }\n\n public float calculateMultiple(EnvParameter parameter) {\n return efficiency.calculateMultiple(this, parameter);\n }\n\n //utils\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterial(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addMaterialRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n materials.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, int amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setIntegerFormat(time):\n new RecipeItemStack(item, amount).setIntegerFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProduction(RecipeItem<?> item, float amount){\n RecipeItemStack res = time > 0?\n new RecipeItemStack(item, amount/time).setFloatFormat(time):\n new RecipeItemStack(item, amount).setFloatFormat();\n\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionPresec(RecipeItem<?> item, float preSeq){\n RecipeItemStack res = new RecipeItemStack(item, preSeq).setPresecFormat();\n productions.put(item, res);\n return res;\n }\n\n public RecipeItemStack addProductionRaw(RecipeItem<?> item, float amount){\n RecipeItemStack res = new RecipeItemStack(item, amount);\n productions.put(item, res);\n return res;\n }\n\n public Recipe setBlock(RecipeItem<?> block){\n this.block = block;\n return this;\n }\n\n public Recipe setTime(float time){\n this.time = time;\n return this;\n }\n\n public Recipe setEfficiency(EffFunc func){\n efficiency = func;\n return this;\n }\n\n public boolean containsProduction(RecipeItem<?> production) {\n return productions.containsKey(production);\n }\n\n public boolean containsMaterial(RecipeItem<?> material) {\n return materials.containsKey(material);\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getOneEff(){\n return ONE_BASE;\n }\n\n /**@see Recipe#getDefaultEff(float) */\n public static EffFunc getZeroEff(){\n return ZERO_BASE;\n }\n\n /**生成一个适用于vanilla绝大多数工厂与设备的效率计算器,若{@linkplain RecipeParser 配方解析器}正确的解释了方块,这个函数应当能够正确计算方块的实际工作效率*/\n public static EffFunc getDefaultEff(float baseEff){\n ObjectFloatMap<Object> attrGroups = new ObjectFloatMap<>();\n\n return new EffFunc() {\n @Override\n public float calculateEff(Recipe recipe, EnvParameter env, float mul) {\n float eff = 1;\n\n attrGroups.clear();\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (stack.isBooster || stack.isAttribute) continue;\n\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul));\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else eff *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/(stack.amount*mul)), stack.optionalCons? 1: 0);\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n eff *= v.next();\n }\n\n return eff*mul;\n }\n\n @Override\n public float calculateMultiple(Recipe recipe, EnvParameter env) {\n attrGroups.clear();\n\n float attr = 0;\n float boost = 1;\n\n for (RecipeItemStack stack : recipe.materials.values()) {\n if (!stack.isBooster && !stack.isAttribute) continue;\n\n if (stack.isAttribute){\n float a = stack.efficiency*Mathf.clamp(env.getAttribute(stack.item)/stack.amount);\n if (stack.maxAttr) attr = Math.max(attr, a);\n else attr += a;\n }\n else {\n if (stack.attributeGroup != null){\n float e = attrGroups.get(stack.attributeGroup, 1)*stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount);\n if (stack.maxAttr) {\n attrGroups.put(stack.attributeGroup, Math.max(attrGroups.get(stack.attributeGroup, 0), e));\n }\n else attrGroups.increment(stack.attributeGroup, 0, e);\n }\n else boost *= Math.max(stack.efficiency*Mathf.clamp(env.getInputs(stack.item)/stack.amount), stack.optionalCons? 1: 0);\n }\n }\n\n ObjectFloatMap.Values v = attrGroups.values();\n while (v.hasNext()) {\n boost *= v.next();\n }\n return boost*(baseEff + attr);\n }\n };\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (!(object instanceof Recipe r)) return false;\n if (r.recipeType != recipeType || r.block != block) return false;\n\n if (r.materials.size != materials.size || r.productions.size != productions.size) return false;\n\n return r.materials.equals(materials) && r.productions.equals(productions);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(recipeType, productions.orderedKeys(), materials.orderedKeys(), block);\n }\n\n public interface EffFunc{\n float calculateEff(Recipe recipe, EnvParameter env, float mul);\n float calculateMultiple(Recipe recipe, EnvParameter env);\n }\n}" }, { "identifier": "RecipeItemStack", "path": "src/main/java/tmi/recipe/RecipeItemStack.java", "snippet": "public class RecipeItemStack {\n /**该条目表示的{@link UnlockableContent}*/\n public final RecipeItem<?> item;\n /**条目附加的数量信息,这将被用作生产计算和显示数据的文本格式化*/\n public float amount;\n\n /**条目数据显示的文本格式化函数,这里返回的文本将显示在条目上以表示数量信息*/\n public AmountFormatter amountFormat = f -> \"\";\n\n /**此条目的效率系数,应当绑定为该条目在生产工作中可用时的最高效率倍率,以参与生产计算*/\n public float efficiency = 1;\n /**该条目是否为可选消耗项,应当与实际情况同步*/\n public boolean optionalCons = false;\n /**该条目是否为属性项目,通常用于计算覆盖/关联的方块提供的属性增益*/\n public boolean isAttribute = false;\n /**该条目是否是增幅项目,若为增幅项目则被单独计算boost倍率,该倍率将影响输入物数量计算并直接乘在最终效率上*/\n public boolean isBooster = false;\n /**条目从属的属性组,一个属性组内的项目在工作效率计算时,会以最高的那一个作为计算结果。\n * <br>\n * 属性组的划分按照提供的对象确定,任意时候当两个条目的属性组对象{@link Object#equals(Object)}为真时就会被视为从属于同一属性组。\n * 该字段默认空,为空时表示该条目不从属于任何属性组*/\n @Nullable public Object attributeGroup = null;\n /**若为真,此消耗项的属性效率计算会按属性组的最大效率计算,否则会对属性效率求和*/\n public boolean maxAttr = false;\n\n public RecipeItemStack(RecipeItem<?> item, float amount) {\n this.item = item;\n this.amount = amount;\n }\n\n public RecipeItemStack(RecipeItem<?> item) {\n this(item, 0);\n }\n\n public RecipeItem<?> item() {\n return item;\n }\n\n public float amount(){\n return amount;\n }\n\n /**获取经过格式化的表示数量的文本信息*/\n public String getAmount() {\n return amountFormat.format(amount);\n }\n\n //属性设置的工具方法\n\n public RecipeItemStack setEfficiency(float efficiency) {\n this.efficiency = efficiency;\n return this;\n }\n\n public RecipeItemStack setOptionalCons(boolean optionalCons) {\n this.optionalCons = optionalCons;\n return this;\n }\n\n public RecipeItemStack setOptionalCons() {\n return setOptionalCons(true);\n }\n\n public RecipeItemStack setAttribute(){\n this.isAttribute = true;\n return this;\n }\n\n public RecipeItemStack setBooster() {\n isBooster = true;\n return this;\n }\n\n public RecipeItemStack setBooster(boolean boost) {\n isBooster = boost;\n return this;\n }\n\n public RecipeItemStack setMaxAttr(){\n this.maxAttr = true;\n return this;\n }\n\n public RecipeItemStack setAttribute(Object group){\n this.attributeGroup = group;\n return this;\n }\n\n public RecipeItemStack setFormat(AmountFormatter format){\n this.amountFormat = format;\n return this;\n }\n\n public RecipeItemStack setEmptyFormat(){\n this.amountFormat = f -> \"\";\n return this;\n }\n\n public RecipeItemStack setFloatFormat(float mul) {\n setFormat(f -> f*mul > 1000? UI.formatAmount(Mathf.round(f*mul)): Strings.autoFixed(f*mul, 1));\n return this;\n }\n\n public RecipeItemStack setIntegerFormat(float mul) {\n setFormat(f -> f*mul > 1000? UI.formatAmount(Mathf.round(f*mul)): Integer.toString(Mathf.round(f*mul)));\n return this;\n }\n\n public RecipeItemStack setFloatFormat() {\n setFormat(f -> f > 1000? UI.formatAmount((long) f): Strings.autoFixed(f, 1));\n return this;\n }\n\n public RecipeItemStack setIntegerFormat() {\n setFormat(f -> f > 1000? UI.formatAmount((long) f): Integer.toString((int) f));\n return this;\n }\n\n public RecipeItemStack setPresecFormat() {\n setFormat(f -> (f*60 > 1000? UI.formatAmount((long) (f*60)): Strings.autoFixed(f*60, 2)) + \"/\" + StatUnit.seconds.localized());\n return this;\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n RecipeItemStack stack = (RecipeItemStack) object;\n return Float.compare(amount, stack.amount) == 0 && isAttribute == stack.isAttribute && isBooster == stack.isBooster && maxAttr == stack.maxAttr && Objects.equals(item, stack.item) && Objects.equals(attributeGroup, stack.attributeGroup);\n }\n\n public interface AmountFormatter {\n String format(float f);\n }\n}" }, { "identifier": "RecipeType", "path": "src/main/java/tmi/recipe/RecipeType.java", "snippet": "public abstract class RecipeType {\n public static final Seq<RecipeType> all = new Seq<>();\n\n public static RecipeType factory,\n building,\n collecting,\n generator;\n\n /**生成{@linkplain RecipeView 配方视图}前对上下文数据进行初始化,并计算布局尺寸\n *\n * @return 表示该布局的长宽尺寸的二元向量*/\n public abstract Vec2 initial(Recipe recipe);\n /**为参数传入的{@link RecipeNode}设置坐标以完成布局*/\n public abstract void layout(RecipeNode recipeNode);\n /**生成从给定起始节点到目标节点的{@linkplain tmi.ui.RecipeView.LineMeta 线条信息}*/\n public abstract RecipeView.LineMeta line(RecipeNode from, RecipeNode to);\n public abstract int id();\n /**向配方显示器内添加显示部件的入口*/\n public void buildView(Group view){}\n\n public static void init() {\n factory = new FactoryRecipe();\n building = new BuildingRecipe();\n collecting = new CollectingRecipe();\n generator = new GeneratorRecipe();\n }\n\n public RecipeType(){\n all.add(this);\n }\n\n public void drawLine(RecipeView recipeView) {\n Draw.scl(recipeView.scaleX, recipeView.scaleY);\n\n for (RecipeView.LineMeta line : recipeView.lines) {\n if (line.vertices.size < 2) continue;\n\n float a = Draw.getColor().a;\n Lines.stroke(Scl.scl(5)*recipeView.scaleX, line.color.get());\n Draw.alpha(Draw.getColor().a*a);\n\n if (line.vertices.size <= 4){\n float x1 = line.vertices.items[0] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[1] - recipeView.getHeight()/2;\n float x2 = line.vertices.items[2] - recipeView.getWidth()/2;\n float y2 = line.vertices.items[3] - recipeView.getHeight()/2;\n Lines.line(\n recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY,\n recipeView.x + recipeView.getWidth()/2 + x2*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y2*recipeView.scaleY\n );\n continue;\n }\n\n Lines.beginLine();\n for (int i = 0; i < line.vertices.size; i += 2) {\n float x1 = line.vertices.items[i] - recipeView.getWidth()/2;\n float y1 = line.vertices.items[i + 1] - recipeView.getHeight()/2;\n\n Lines.linePoint(recipeView.x + recipeView.getWidth()/2 + x1*recipeView.scaleX, recipeView.y + recipeView.getHeight()/2 + y1*recipeView.scaleY);\n }\n Lines.endLine();\n }\n\n Draw.reset();\n }\n\n @Override\n public int hashCode() {\n return id();\n }\n}" }, { "identifier": "PowerMark", "path": "src/main/java/tmi/recipe/types/PowerMark.java", "snippet": "public class PowerMark extends RecipeItem<String> {\n public static PowerMark INSTANCE = TooManyItems.itemsManager.addItemWrap(\"power-mark\", new PowerMark());\n\n private PowerMark() {\n super(\"power-mark\");\n }\n\n @Override\n public int ordinal() {\n return -1;\n }\n\n @Override\n public int typeID() {\n return -1;\n }\n\n @Override\n public String name() {\n return item;\n }\n\n @Override\n public String localizedName() {\n return Core.bundle.get(\"tmi.\" + item);\n }\n\n @Override\n public TextureRegion icon() {\n return Icon.power.getRegion();\n }\n\n @Override\n public boolean hidden() {\n return false;\n }\n}" } ]
import arc.math.Mathf; import arc.struct.Seq; import mindustry.Vars; import mindustry.content.Blocks; import mindustry.world.Block; import mindustry.world.blocks.environment.Floor; import mindustry.world.blocks.power.ThermalGenerator; import tmi.recipe.Recipe; import tmi.recipe.RecipeItemStack; import tmi.recipe.RecipeType; import tmi.recipe.types.PowerMark;
4,649
package tmi.recipe.parser; public class ThermalGeneratorParser extends ConsumerParser<ThermalGenerator>{ {excludes.add(GeneratorParser.class);} @Override public boolean isTarget(Block content) { return content instanceof ThermalGenerator; } @Override
package tmi.recipe.parser; public class ThermalGeneratorParser extends ConsumerParser<ThermalGenerator>{ {excludes.add(GeneratorParser.class);} @Override public boolean isTarget(Block content) { return content instanceof ThermalGenerator; } @Override
public Seq<Recipe> parse(ThermalGenerator content) {
0
2023-11-05 11:39:21+00:00
8k
dulaiduwang003/DeepSee
microservices/ts-drawing/src/main/java/com/cn/service/impl/DallServiceImpl.java
[ { "identifier": "DallCommon", "path": "microservices/ts-drawing/src/main/java/com/cn/common/DallCommon.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class DallCommon {\n\n\n private final DallDefaultConfiguration configuration;\n public static final DallStructure STRUCTURE = new DallStructure();\n private static final AtomicInteger counter = new AtomicInteger(0);\n\n /**\n * 轮询获取KEY配置\n *\n * @return the string\n */\n public static String pollGetKey() {\n //获取集合KEY\n List<String> keyCistern =STRUCTURE.getKeyList();\n //遍历获取\n int index = counter.getAndIncrement() % keyCistern.size();\n return keyCistern.get(index);\n }\n\n /**\n * 初始化.\n */\n @PostConstruct\n public void init() {\n STRUCTURE\n .setKeyList(Arrays.asList(configuration.getKeyList()))\n .setRequestUrl(configuration.getRequestUrl());\n }\n\n\n}" }, { "identifier": "DrawingConstant", "path": "microservices/ts-drawing/src/main/java/com/cn/constant/DrawingConstant.java", "snippet": "public interface DrawingConstant {\n\n\n String TASK = \"TASK:\";\n String SD_TASK_QUEUE = \"SD_TASK_QUEUE\";\n String SD_EXECUTION = \"SD_EXECUTION\";\n\n String DALL_TASK_QUEUE = \"DALL_TASK_QUEUE\";\n String DALL_EXECUTION = \"DALL_EXECUTION\";\n}" }, { "identifier": "DrawingStatusConstant", "path": "microservices/ts-drawing/src/main/java/com/cn/constant/DrawingStatusConstant.java", "snippet": "public interface DrawingStatusConstant {\n\n String DISUSE = \"DISUSE\";\n String PENDING = \"PENDING\";\n String PROCESSING = \"PROCESSING\";\n String SUCCEED = \"SUCCEED\";\n\n\n}" }, { "identifier": "DallTaskDto", "path": "microservices/ts-drawing/src/main/java/com/cn/dto/DallTaskDto.java", "snippet": "@Data\n@Accessors(chain = true)\n@SuppressWarnings(\"all\")\npublic class DallTaskDto {\n\n @NotBlank(message = \"提示词不能为空\")\n private String prompt;\n\n @NotNull(message = \"图片大小不能为空\")\n private String size;\n\n private String mask;\n\n private String image;\n}" }, { "identifier": "DialogueImageDto", "path": "microservices/ts-drawing/src/main/java/com/cn/dto/DialogueImageDto.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DialogueImageDto {\n\n @NotBlank(message = \"prompt word cannot be empty\")\n private String prompt;\n\n// @NotBlank(message = \"size cannot be empty\")\n// private String size;\n\n\n}" }, { "identifier": "TsDialogueDrawing", "path": "microservices/ts-drawing/src/main/java/com/cn/entity/TsDialogueDrawing.java", "snippet": "@Data\n@TableName(value = \"ts_dialogue_drawing\")\n@Accessors(chain = true)\npublic class TsDialogueDrawing {\n\n @TableId(type = IdType.AUTO)\n private Long dialogueDrawingId;\n\n private String url;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createdTime;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime updateTime;\n\n\n}" }, { "identifier": "TsGenerateDrawing", "path": "microservices/ts-drawing/src/main/java/com/cn/entity/TsGenerateDrawing.java", "snippet": "@Data\n@TableName(value = \"ts_generate_drawing\")\n@Accessors(chain = true)\npublic class TsGenerateDrawing {\n\n @TableId(type = IdType.INPUT)\n private String generateDrawingId;\n\n private String prompt;\n\n private Long userId;\n\n private String status;\n\n private String url;\n\n private String type;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createdTime;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime updateTime;\n\n\n}" }, { "identifier": "DrawingTypeEnum", "path": "microservices/ts-drawing/src/main/java/com/cn/enums/DrawingTypeEnum.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Getter\npublic enum DrawingTypeEnum {\n\n DALL(\"DALL\"),\n\n SD(\"SD\");\n\n\n String dec;\n\n\n}" }, { "identifier": "FileEnum", "path": "microservices/ts-common/src/main/java/com/cn/enums/FileEnum.java", "snippet": "@Getter\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic enum FileEnum {\n\n //头像\n AVATAR(\"avatar\"),\n //绘图\n DRAWING(\"drawing\");\n\n String dec;\n\n}" }, { "identifier": "DallException", "path": "microservices/ts-drawing/src/main/java/com/cn/exception/DallException.java", "snippet": "@SuppressWarnings(\"all\")\n@Data\npublic class DallException extends RuntimeException {\n\n private String message;\n\n private Integer code;\n\n\n public DallException(final String message, final Integer code) {\n super(message);\n this.message = message;\n this.code = code;\n }\n\n public DallException(final String message) {\n super(message);\n this.message = message;\n this.code = 500;\n }\n}" }, { "identifier": "TsDialogueDrawingMapper", "path": "microservices/ts-drawing/src/main/java/com/cn/mapper/TsDialogueDrawingMapper.java", "snippet": "@Mapper\npublic interface TsDialogueDrawingMapper extends BaseMapper<TsDialogueDrawing> {\n}" }, { "identifier": "TsGenerateDrawingMapper", "path": "microservices/ts-drawing/src/main/java/com/cn/mapper/TsGenerateDrawingMapper.java", "snippet": "@Mapper\npublic interface TsGenerateDrawingMapper extends BaseMapper<TsGenerateDrawing> {\n}" }, { "identifier": "DallModel", "path": "microservices/ts-drawing/src/main/java/com/cn/model/DallModel.java", "snippet": "@Data\n@Accessors(chain = true)\n@SuppressWarnings(\"all\")\npublic class DallModel {\n\n private String model = \"dall-e-2\";\n\n private String prompt;\n\n private String size;\n\n private String mask;\n\n private String image;\n\n private Integer n = 1;\n\n}" }, { "identifier": "DialogueGenerateModel", "path": "microservices/ts-drawing/src/main/java/com/cn/model/DialogueGenerateModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DialogueGenerateModel implements Serializable {\n\n private String model = \"dall-e-3\";\n\n private String prompt;\n\n// private String size = \"512x512\";\n//\n// private String quality = \"standard\";\n//\n// private Integer n = 1;\n}" }, { "identifier": "DallService", "path": "microservices/ts-drawing/src/main/java/com/cn/service/DallService.java", "snippet": "public interface DallService {\n\n\n DialogueImageVo dialogGenerationImg(final DialogueImageDto dto);\n\n\n String addDallTask(final DallTaskDto dto);\n}" }, { "identifier": "TaskStructure", "path": "microservices/ts-drawing/src/main/java/com/cn/structure/TaskStructure.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class TaskStructure implements Serializable {\n\n private String drawingType;\n\n private String taskId;\n\n private String prompt;\n\n private String imageUrl;\n\n private String status;\n\n private Object extra;\n\n}" }, { "identifier": "BaiduTranslationUtil", "path": "microservices/ts-drawing/src/main/java/com/cn/utils/BaiduTranslationUtil.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class BaiduTranslationUtil {\n\n @Value(\"${baidu-translation.appid}\")\n private String appid;\n\n @Value(\"${baidu-translation.secret}\")\n private String secret;\n\n private static final String URL = \"https://api.fanyi.baidu.com/api/trans/vip/translate\";\n\n private final WebClient.Builder webClientBuilder;\n\n public String translate(String parameter, String to) throws Exception {\n Random random = new Random(10);\n String salt = Integer.toString(random.nextInt());\n String appid = this.appid + parameter + salt + this.secret;\n String sign = SaSecureUtil.md5(appid);\n // 封装请求参数\n MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();\n paramMap.add(\"q\", parameter);\n paramMap.add(\"appid\", this.appid);\n paramMap.add(\"salt\", salt);\n paramMap.add(\"sign\", sign);\n paramMap.add(\"from\", \"auto\");\n paramMap.add(\"to\", to);\n final WebClient build = webClientBuilder\n .baseUrl(URL)\n .build();\n // 发送POST请求,获取结果\n final String block = build.post()\n .uri(UriBuilder::build)\n .contentType(MediaType.APPLICATION_FORM_URLENCODED)\n .body(BodyInserters.fromFormData(paramMap))\n .retrieve()\n .bodyToMono(String.class)\n .block();\n final JSONObject jsonObject = JSONObject.parseObject(block);\n assert jsonObject != null;\n final JSONArray transResult = jsonObject.getJSONArray(\"trans_result\");\n return transResult.getJSONObject(0).getString(\"dst\");\n }\n\n public String chineseTranslation(final String parameter) throws Exception {\n return translate(parameter, \"zh\");\n }\n\n public String englishTranslation(final String parameter) throws Exception {\n return translate(parameter, \"en\");\n }\n\n}" }, { "identifier": "DrawingUtils", "path": "microservices/ts-drawing/src/main/java/com/cn/utils/DrawingUtils.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class DrawingUtils {\n\n private final TsGenerateDrawingMapper tsGenerateDrawingMapper;\n public Long verifyTask() {\n final Long currentLoginId = UserUtils.getCurrentLoginId();\n final Long taskCount = tsGenerateDrawingMapper.selectCount(new QueryWrapper<TsGenerateDrawing>()\n .lambda()\n .eq(TsGenerateDrawing::getUserId, currentLoginId)\n .eq(TsGenerateDrawing::getStatus, DrawingStatusConstant.PENDING)\n .or()\n .eq(TsGenerateDrawing::getStatus, DrawingStatusConstant.PROCESSING)\n );\n final Integer maximumTask = PoolCommon.STRUCTURE.getMaximumTask();\n if (taskCount > maximumTask) {\n throw new DrawingException(\"目前,最多可以创建 \" + maximumTask + \" 任务\");\n }\n return currentLoginId;\n }\n\n}" }, { "identifier": "RedisUtils", "path": "microservices/ts-chat/src/main/java/com/cn/utils/RedisUtils.java", "snippet": "@Component\n@SuppressWarnings(\"all\")\n@RequiredArgsConstructor\npublic final class RedisUtils {\n\n private final RedisTemplate<String, Object> redisTemplate;\n\n public RedisTemplate getRedisTemplate() {\n return this.redisTemplate;\n }\n\n\n public boolean expire(final String key, final long timeout) {\n return expire(key, timeout, TimeUnit.SECONDS);\n }\n\n public Long getExpire(final String key) {\n return redisTemplate.getExpire(key);\n }\n\n\n public boolean expire(final String key, final long timeout, final TimeUnit unit) {\n Boolean ret = redisTemplate.expire(key, timeout, unit);\n return ret != null && ret;\n }\n\n public boolean hasKey(final String key) {\n return redisTemplate.hasKey(key);\n }\n\n public long increment(final String key, final long delta) {\n return redisTemplate.opsForValue().increment(key, delta);\n }\n\n public boolean delKey(final String key) {\n Boolean ret = redisTemplate.delete(key);\n return ret != null && ret;\n }\n\n\n public long delKeys(final Collection<String> keys) {\n Long ret = redisTemplate.delete(keys);\n return ret == null ? 0 : ret;\n }\n\n\n public void setValue(final String key, final Object value) {\n redisTemplate.opsForValue().set(key, value);\n }\n\n\n public void setValueTimeout(final String key, final Object value, final long timeout) {\n redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);\n }\n\n\n public Object getValue(final String key) {\n return redisTemplate.opsForValue().get(key);\n }\n\n\n public boolean hasHashKey(final String key, String hkey) {\n Boolean ret = redisTemplate.opsForHash().hasKey(key, hkey);\n return ret != null && ret;\n }\n\n\n public void hashPut(final String key, final String hKey, final Object value) {\n redisTemplate.opsForHash().put(key, hKey, value);\n }\n\n\n public void hashPutAll(final String key, final Map<String, Object> values) {\n redisTemplate.opsForHash().putAll(key, values);\n }\n\n\n public Object hashGet(final String key, final String hKey) {\n return redisTemplate.opsForHash().get(key, hKey);\n }\n\n\n public Map<Object, Object> hashGetAll(final String key) {\n return redisTemplate.opsForHash().entries(key);\n }\n\n\n public List<Object> hashMultiGet(final String key, final Collection<Object> hKeys) {\n return redisTemplate.opsForHash().multiGet(key, hKeys);\n }\n\n public boolean hashExists(String key, String hashKey) {\n return redisTemplate.opsForHash().hasKey(key, hashKey);\n }\n\n\n public long hashDeleteKeys(final String key, final Collection<Object> hKeys) {\n return redisTemplate.opsForHash().delete(key, hKeys);\n }\n\n public Long hashDelete(final String key, final Object... hashKey) {\n return redisTemplate.opsForHash().delete(key, hashKey);\n }\n\n\n public long setSet(final String key, final Object... values) {\n Long count = redisTemplate.opsForSet().add(key, values);\n return count == null ? 0 : count;\n }\n\n\n public long setDel(final String key, final Object... values) {\n Long count = redisTemplate.opsForSet().remove(key, values);\n return count == null ? 0 : count;\n }\n\n\n public Set<Object> getSetAll(final String key) {\n return redisTemplate.opsForSet().members(key);\n }\n\n\n public long zsetSetAll(final String key, final Set<ZSetOperations.TypedTuple<Object>> values) {\n Long count = redisTemplate.opsForZSet().add(key, values);\n return count == null ? 0 : count;\n }\n\n public Double zsetSetGetSource(final String key, final Object value) {\n\n\n return redisTemplate.opsForZSet().score(key, value);\n }\n\n public Double zsetIncrementScore(final String key, final Object value, final Double increment) {\n return redisTemplate.opsForZSet().incrementScore(key, value, increment);\n }\n\n public Boolean zsetSet(final String key, final Object values, final Double source) {\n final Boolean add = redisTemplate.opsForZSet().add(key, values, source);\n return add;\n }\n\n\n public Set<ZSetOperations.TypedTuple<Object>> zsetReverseRangeWithScores(final String key, final Long start, final Long end) {\n return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);\n }\n\n\n public Set<Object> zsetReverseRange(final String key, final Long start, final Long end) {\n return redisTemplate.opsForZSet().reverseRange(key, start, end);\n }\n\n\n public long selfIncrease(final String key) {\n return redisTemplate.execute(new SessionCallback<Long>() {\n @Override\n public Long execute(RedisOperations operations) throws DataAccessException {\n operations.multi();\n Long count = operations.opsForValue().increment(key);\n operations.exec();\n return count;\n }\n });\n }\n\n public Double selfIncreaseSource(final String key, final Object value) {\n return redisTemplate.execute(new SessionCallback<Double>() {\n @Override\n public Double execute(RedisOperations operations) throws DataAccessException {\n operations.multi();\n Double count = operations.opsForZSet().incrementScore(key, value, 1);\n operations.exec();\n return count;\n }\n });\n }\n\n public long zsetDelAll(final String key, final Set<ZSetOperations.TypedTuple<Object>> values) {\n Long count = redisTemplate.opsForZSet().remove(key, values);\n return count == null ? 0 : count;\n }\n\n public long zsetDel(final String key, Object values) {\n Long count = redisTemplate.opsForZSet().remove(key, values);\n return count == null ? 0 : count;\n }\n\n public long listPush(final String key, final Object value) {\n Long count = redisTemplate.opsForList().rightPush(key, value);\n return count == null ? 0 : count;\n }\n\n public Boolean doesItExist(final String key) {\n return redisTemplate.hasKey(key);\n }\n\n public long listPushAll(final String key, final Collection<Object> values) {\n Long count = redisTemplate.opsForList().rightPushAll(key, values);\n return count == null ? 0 : count;\n }\n\n public long listPushAll(final String key, final Object... values) {\n Long count = redisTemplate.opsForList().rightPushAll(key, values);\n return count == null ? 0 : count;\n }\n\n\n public List<Object> listGet(final String key, final int start, final int end) {\n return redisTemplate.opsForList().range(key, start, end);\n }\n\n public Long keySize(final String key) {\n return redisTemplate.opsForList().size(key);\n }\n}" }, { "identifier": "UploadUtil", "path": "microservices/ts-common/src/main/java/com/cn/utils/UploadUtil.java", "snippet": "@Component\n@SuppressWarnings(\"all\")\n@Slf4j\npublic class UploadUtil {\n\n @Value(\"${oss.ali-oss.endpoint}\")\n private String endpoint;\n\n @Value(\"${oss.ali-oss.accessKey}\")\n private String accessKey;\n\n @Value(\"${oss.ali-oss.secretKey}\")\n private String secretKey;\n\n @Value(\"${oss.ali-oss.bucketName}\")\n private String bucketName;\n\n public String uploadFile(final MultipartFile file, final String path) {\n\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try (InputStream inputStream = file.getInputStream()) {\n String originalFileName = file.getOriginalFilename();\n\n assert originalFileName != null;\n String fileName;\n fileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf('.'));\n\n String filePath = path + \"/\" + fileName;\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/png\");\n ossClient.putObject(bucketName, filePath, inputStream, objectMetadata);\n return \"/\" + filePath;\n\n } catch (IOException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n public String uploadImageFromUrl(String imageUrl, String path) {\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try {\n // 生成随机的图片名称\n String fileName = path + \"/\" + UUID.randomUUID().toString() + \".png\";\n\n\n // 通过URL下载网络图片到本地\n URL url = new URL(imageUrl);\n InputStream inputStream = url.openStream();\n // 上传图片到OSS\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/jpg\");\n ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);\n return \"/\" + fileName;\n } catch (IOException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n public String uploadBase64Image(final String base64Image, String path) {\n OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);\n try {\n // 使用UUID生成新的文件名\n String fileName = path + \"/\" + UUID.randomUUID().toString() + \".jpg\";\n // 将Base64图片转换为字节数组\n byte[] imageBytes = Base64.getDecoder().decode(base64Image);\n ObjectMetadata objectMetadata = new ObjectMetadata();\n objectMetadata.setContentType(\"image/jpg\");\n // 创建PutObjectRequest对象并上传图片\n PutObjectRequest request = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(imageBytes), objectMetadata);\n ossClient.putObject(request);\n return \"/\" + fileName;\n } catch (Exception e) {\n throw new OSSException();\n } finally {\n // 关闭OSS客户端\n ossClient.shutdown();\n }\n\n }\n\n public void deletedFile(final String path) {\n OSS ossClient = new OSSClientBuilder()\n .build(endpoint, accessKey, secretKey);\n try {\n\n if (path.startsWith(\"/\")) {\n ossClient.deleteObject(bucketName, path.substring(1));\n } else {\n ossClient.deleteObject(bucketName, path);\n }\n } catch (OSSException | ClientException e) {\n throw new OSSException();\n } finally {\n ossClient.shutdown();\n }\n }\n\n}" }, { "identifier": "DialogueImageVo", "path": "microservices/ts-drawing/src/main/java/com/cn/vo/DialogueImageVo.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DialogueImageVo {\n\n private String revisedPrompt;\n\n\n private String url;\n}" } ]
import com.alibaba.fastjson.JSONObject; import com.cn.common.DallCommon; import com.cn.constant.DrawingConstant; import com.cn.constant.DrawingStatusConstant; import com.cn.dto.DallTaskDto; import com.cn.dto.DialogueImageDto; import com.cn.entity.TsDialogueDrawing; import com.cn.entity.TsGenerateDrawing; import com.cn.enums.DrawingTypeEnum; import com.cn.enums.FileEnum; import com.cn.exception.DallException; import com.cn.mapper.TsDialogueDrawingMapper; import com.cn.mapper.TsGenerateDrawingMapper; import com.cn.model.DallModel; import com.cn.model.DialogueGenerateModel; import com.cn.service.DallService; import com.cn.structure.TaskStructure; import com.cn.utils.BaiduTranslationUtil; import com.cn.utils.DrawingUtils; import com.cn.utils.RedisUtils; import com.cn.utils.UploadUtil; import com.cn.vo.DialogueImageVo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.util.UUID;
5,914
package com.cn.service.impl; @Service @Slf4j @RequiredArgsConstructor public class DallServiceImpl implements DallService { private final BaiduTranslationUtil baiduTranslationUtil; private final TsDialogueDrawingMapper tsDialogueDrawingMapper; private final TsGenerateDrawingMapper tsGenerateDrawingMapper; private final UploadUtil uploadUtil; private final DrawingUtils drawingUtils; private final RedisUtils redisUtils; private final RedisTemplate<String, Object> redisTemplate; @Override @Transactional(rollbackFor = Exception.class) public DialogueImageVo dialogGenerationImg(final DialogueImageDto dto) { final String block = WebClient.builder().baseUrl(DallCommon.STRUCTURE.getRequestUrl()).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + DallCommon.pollGetKey()).codecs(item -> item.defaultCodecs().maxInMemorySize(20 * 1024 * 1024)).build().post().uri("/images/generations").body(BodyInserters.fromValue(new DialogueGenerateModel().setPrompt(dto.getPrompt()))).retrieve().onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), response -> response.bodyToMono(String.class).flatMap(errorBody -> { final String errorCode = JSONObject.parseObject(errorBody).getString("error"); final JSONObject jsonObject = JSONObject.parseObject(errorCode); final String code = jsonObject.getString("code"); if ("rate_limit_exceeded".equals(code)) { log.warn("DALL-3 已经超过官方限制速率"); return Mono.error(new DallException("🥲 Sorry! 当前绘图人数过多,请稍后重试~")); } return Mono.error(new DallException("🥲 Sorry! 当前对话绘图服务可能出了点问题,请联系管理员解决~")); })).bodyToMono(String.class).block(); //解析JSON final JSONObject jsonObject = JSONObject.parseObject(block); final JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0); String revisedPrompt = data.getString("revised_prompt"); //上传数据到阿里云OSS 不然回显过慢 final String url = uploadUtil.uploadImageFromUrl(data.getString("url"), FileEnum.DRAWING.getDec()); tsDialogueDrawingMapper.insert(new TsDialogueDrawing().setUrl(url)); synchronized (this) { try { //百度翻译API 单 1秒qs revisedPrompt = baiduTranslationUtil.chineseTranslation(revisedPrompt); } catch (Exception e) { log.warn("调取百度翻译API失败 信息:{} 位置:{}", e.getMessage(), e.getClass()); } } return new DialogueImageVo().setRevisedPrompt(revisedPrompt).setUrl(url); } @Override
package com.cn.service.impl; @Service @Slf4j @RequiredArgsConstructor public class DallServiceImpl implements DallService { private final BaiduTranslationUtil baiduTranslationUtil; private final TsDialogueDrawingMapper tsDialogueDrawingMapper; private final TsGenerateDrawingMapper tsGenerateDrawingMapper; private final UploadUtil uploadUtil; private final DrawingUtils drawingUtils; private final RedisUtils redisUtils; private final RedisTemplate<String, Object> redisTemplate; @Override @Transactional(rollbackFor = Exception.class) public DialogueImageVo dialogGenerationImg(final DialogueImageDto dto) { final String block = WebClient.builder().baseUrl(DallCommon.STRUCTURE.getRequestUrl()).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + DallCommon.pollGetKey()).codecs(item -> item.defaultCodecs().maxInMemorySize(20 * 1024 * 1024)).build().post().uri("/images/generations").body(BodyInserters.fromValue(new DialogueGenerateModel().setPrompt(dto.getPrompt()))).retrieve().onStatus(status -> status.is4xxClientError() || status.is5xxServerError(), response -> response.bodyToMono(String.class).flatMap(errorBody -> { final String errorCode = JSONObject.parseObject(errorBody).getString("error"); final JSONObject jsonObject = JSONObject.parseObject(errorCode); final String code = jsonObject.getString("code"); if ("rate_limit_exceeded".equals(code)) { log.warn("DALL-3 已经超过官方限制速率"); return Mono.error(new DallException("🥲 Sorry! 当前绘图人数过多,请稍后重试~")); } return Mono.error(new DallException("🥲 Sorry! 当前对话绘图服务可能出了点问题,请联系管理员解决~")); })).bodyToMono(String.class).block(); //解析JSON final JSONObject jsonObject = JSONObject.parseObject(block); final JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0); String revisedPrompt = data.getString("revised_prompt"); //上传数据到阿里云OSS 不然回显过慢 final String url = uploadUtil.uploadImageFromUrl(data.getString("url"), FileEnum.DRAWING.getDec()); tsDialogueDrawingMapper.insert(new TsDialogueDrawing().setUrl(url)); synchronized (this) { try { //百度翻译API 单 1秒qs revisedPrompt = baiduTranslationUtil.chineseTranslation(revisedPrompt); } catch (Exception e) { log.warn("调取百度翻译API失败 信息:{} 位置:{}", e.getMessage(), e.getClass()); } } return new DialogueImageVo().setRevisedPrompt(revisedPrompt).setUrl(url); } @Override
public String addDallTask(final DallTaskDto dto) {
3
2023-11-05 16:26:39+00:00
8k
373675032/xw-fast
xw-fast-crud/src/main/java/world/xuewei/fast/crud/controller/BaseController.java
[ { "identifier": "BusinessRunTimeException", "path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/BusinessRunTimeException.java", "snippet": "@Setter\n@Getter\npublic class BusinessRunTimeException extends RuntimeException {\n\n private static final long serialVersionUID = -4879677283847539655L;\n\n protected int code;\n\n protected String message;\n\n public BusinessRunTimeException(int code, String message) {\n super(message);\n this.code = code;\n this.message = message;\n }\n\n public BusinessRunTimeException(String message, Object... objects) {\n super(message);\n for (Object o : objects) {\n message = message.replaceFirst(\"\\\\{\\\\}\", o.toString());\n }\n this.message = message;\n }\n\n /**\n * 设置原因\n *\n * @param cause 原因\n */\n public BusinessRunTimeException setCause(Throwable cause) {\n this.initCause(cause);\n return this;\n }\n}" }, { "identifier": "ParamEmptyException", "path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/ParamEmptyException.java", "snippet": "public class ParamEmptyException extends BusinessRunTimeException {\n\n private static final long serialVersionUID = -4879677283847539655L;\n\n public ParamEmptyException(int code, String message) {\n super(code, message);\n this.code = code;\n this.message = message;\n }\n\n public ParamEmptyException(String message, Object... objects) {\n super(\"\");\n for (Object o : objects) {\n message = message.replaceFirst(\"\\\\{\\\\}\", o.toString());\n }\n super.setMessage(message);\n this.message = message;\n }\n\n public static ParamEmptyException build(String param) {\n throw new ParamEmptyException(\"参数<\" + param + \">为空\");\n }\n\n /**\n * 设置原因\n *\n * @param cause 原因\n */\n public ParamEmptyException setCause(Throwable cause) {\n this.initCause(cause);\n return this;\n }\n}" }, { "identifier": "ReqBody", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/dto/request/ReqBody.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ReqBody<T> {\n\n /**\n * 实体对象\n */\n private T obj;\n\n /**\n * 实体对象列表\n */\n private List<T> objs;\n\n /**\n * ID\n */\n private Serializable id;\n\n /**\n * ID 数组\n */\n private List<Serializable> ids;\n\n /**\n * 字段名\n */\n private String field;\n\n /**\n * 值\n */\n private Object value;\n\n /**\n * 值数组\n */\n private List<Object> values;\n\n /**\n * 自定义查询体\n */\n private QueryBody<T> queryBody;\n}" }, { "identifier": "QueryBody", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/query/QueryBody.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class QueryBody<T> {\n\n /**\n * 关键词查询内容\n */\n private String keyword;\n\n /**\n * 关键字查询字段\n */\n private List<String> keywordFields;\n\n /**\n * 结果返回指定字段\n */\n private List<String> includeFields;\n\n /**\n * 查询条件\n */\n private List<QueryCondition> conditions;\n\n /**\n * 排序信息\n */\n private List<QueryOrder> orderBy;\n\n /**\n * 分页信息\n */\n private QueryPage pageBy;\n\n /**\n * 参数合法性检查\n */\n public void check() {\n if (ObjectUtil.isNotEmpty(keyword) && ObjectUtil.isEmpty(keywordFields)) {\n throw new BusinessRunTimeException(\"关键词查询时必须指定 keywordFields,且必须指定为字符类型字段\");\n }\n if (ObjectUtil.isNotEmpty(conditions)) {\n conditions.forEach(QueryCondition::check);\n }\n if (ObjectUtil.isNotEmpty(orderBy)) {\n orderBy.forEach(QueryOrder::check);\n }\n }\n\n /**\n * 构建 QueryWrapper\n *\n * @return QueryWrapper\n */\n public QueryWrapper<T> buildWrapper() {\n QueryWrapper<T> wrapper = new QueryWrapper<>();\n // 关键词\n if (ObjectUtil.isNotEmpty(keywordFields) && ObjectUtil.isNotEmpty(keyword)) {\n wrapper.and(orWrapper -> {\n for (String keywordField : keywordFields) {\n orWrapper.like(VariableNameUtils.humpToLine(keywordField), keyword).or();\n }\n });\n }\n // 指定查询字段\n if (ObjectUtil.isNotEmpty(includeFields)) {\n String[] array = includeFields.stream().map(VariableNameUtils::humpToLine).collect(Collectors.toList()).toArray(new String[]{});\n wrapper.select(array);\n }\n // 查询条件\n if (ObjectUtil.isNotEmpty(conditions)) {\n for (QueryCondition condition : conditions) {\n String field = VariableNameUtils.humpToLine(condition.getField());\n String type = condition.getType();\n Object value = condition.getValue();\n if (\"ALL_DATA\".equals(value)) {\n continue;\n }\n switch (type) {\n case \"eq\": // 等于 =\n wrapper.eq(field, value);\n break;\n case \"ne\": // 不等于 <>\n wrapper.ne(field, value);\n break;\n case \"gt\": // 大于 >\n wrapper.gt(field, value);\n break;\n case \"ge\": // 大于等于 >=\n wrapper.ge(field, value);\n break;\n case \"lt\": // 小于 <\n wrapper.lt(field, value);\n break;\n case \"le\": // 小于等于 <=\n wrapper.le(field, value);\n break;\n case \"contain\": // LIKE '%值%'\n wrapper.like(field, value);\n break;\n case \"notContain\": // NOT LIKE '%值%'\n wrapper.notLike(field, value);\n break;\n case \"startWith\": // LIKE '%值'\n wrapper.likeLeft(field, value);\n break;\n case \"endWith\": // LIKE '值%'\n wrapper.likeRight(field, value);\n break;\n case \"isNull\": // 字段 IS NULL\n wrapper.isNull(field);\n break;\n case \"isNotNull\": // 字段 IS NOT NULL\n wrapper.isNotNull(field);\n break;\n case \"in\": // 字段 IN (value.get(0), value.get(1), ...)\n try {\n wrapper.in(field, parseValue2List(value).toArray());\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"in 操作的值必须为数组\");\n }\n break;\n case \"notIn\": // 字段 NOT IN (value.get(0), value.get(1), ...)\n try {\n wrapper.notIn(field, parseValue2List(value).toArray());\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"notIn 操作的值必须为数组\");\n }\n break;\n case \"between\": // BETWEEN 值1 AND 值2\n try {\n List<Object> betweenList = parseValue2List(value);\n if (betweenList.size() != 2) {\n throw new BusinessRunTimeException(\"between 操作的值必须为数组且长度为 2\");\n }\n wrapper.between(field, betweenList.get(0), betweenList.get(1));\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"between 操作的值必须为数组且长度为 2\");\n }\n break;\n case \"notBetween\": // NOT BETWEEN 值1 AND 值2\n try {\n List<Object> betweenList = parseValue2List(value);\n if (betweenList.size() != 2) {\n throw new BusinessRunTimeException(\"notBetween 操作的值必须为数组且长度为 2\");\n }\n wrapper.notBetween(field, betweenList.get(0), betweenList.get(1));\n } catch (IOException e) {\n throw new BusinessRunTimeException(\"notBetween 操作的值必须为数组且长度为 2\");\n }\n break;\n default:\n throw new BusinessRunTimeException(\"不支持的查询操作:\" + type);\n }\n }\n }\n // 排序\n if (ObjectUtil.isNotEmpty(orderBy)) {\n for (QueryOrder queryOrder : orderBy) {\n String field = VariableNameUtils.humpToLine(queryOrder.getField());\n String type = queryOrder.getType().toLowerCase();\n switch (type) {\n case \"asc\":\n wrapper.orderByAsc(field);\n break;\n case \"desc\":\n wrapper.orderByDesc(field);\n break;\n default:\n throw new BusinessRunTimeException(\"不支持的排序操作:\" + type);\n }\n }\n }\n return wrapper;\n }\n\n /**\n * 构建 IPage\n *\n * @return IPage\n */\n public IPage<T> buildPage() {\n if (ObjectUtil.isEmpty(pageBy) || (ObjectUtil.isEmpty(pageBy.getPageNum()) && ObjectUtil.isEmpty(pageBy.getPageSize()))) {\n return null;\n }\n if (ObjectUtil.isEmpty(pageBy.getPageNum()) || ObjectUtil.isEmpty(pageBy.getPageSize())) {\n throw new BusinessRunTimeException(\"pageNum 与 pageSize 必须同时指定\");\n }\n return new Page<>(pageBy.getPageNum(), pageBy.getPageSize());\n }\n\n /**\n * 将 Object 类型的对象(实际上是 JsonArray) 转为 List\n *\n * @param value 对象\n * @return List\n * @throws IOException JSON 解析异常\n */\n private List<Object> parseValue2List(Object value) throws IOException {\n ObjectMapper objectMapper = new ObjectMapper();\n CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, Object.class);\n return objectMapper.readValue(String.valueOf(value), listType);\n }\n}" }, { "identifier": "ResultPage", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/query/ResultPage.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(callSuper = true)\npublic class ResultPage<T> extends QueryPage {\n\n /**\n * 总记录数\n */\n private Long totalRecord;\n\n /**\n * 总页数\n */\n private Long totalPage;\n\n /**\n * 记录结果\n */\n private List<T> records;\n\n /**\n * 转换分页信息\n *\n * @param wrapperPage Mybatis Pulse分页信息\n */\n public ResultPage(IPage<T> wrapperPage) {\n if (ObjectUtil.isNotEmpty(wrapperPage)) {\n this.pageNum = wrapperPage.getCurrent();\n this.pageSize = wrapperPage.getSize();\n this.totalPage = wrapperPage.getPages();\n this.totalRecord = wrapperPage.getTotal();\n this.records = wrapperPage.getRecords();\n }\n }\n}" }, { "identifier": "BaseDBService", "path": "xw-fast-crud/src/main/java/world/xuewei/fast/crud/service/BaseDBService.java", "snippet": "public class BaseDBService<T> extends ServiceImpl<BaseMapper<T>, T> implements BaseDBInterface<T> {\n\n private final BaseMapper<T> mapper;\n\n public BaseDBService(BaseMapper<T> mapper) {\n this.mapper = mapper;\n }\n\n @Override\n public T saveData(T obj) {\n super.saveOrUpdate(obj);\n return obj;\n }\n\n @Override\n public List<T> saveBatchData(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.saveBatchData(objList);\n }\n\n @Transactional(rollbackFor = Exception.class)\n @Override\n public List<T> saveBatchData(Collection<T> list) {\n // 循环新增,若数据量大可自行扩展\n list.forEach(this::saveData);\n return new ArrayList<>(list);\n }\n\n @Override\n public T insert(T obj) {\n mapper.insert(obj);\n return obj;\n }\n\n @Override\n public List<T> insertBatch(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.insertBatch(objList);\n }\n\n @Override\n public List<T> insertBatch(Collection<T> list) {\n super.saveBatch(list);\n return new ArrayList<>(list);\n }\n\n @Override\n public T update(T obj) {\n mapper.updateById(obj);\n return obj;\n }\n\n @Override\n public List<T> updateBatch(T[] array) {\n List<T> objList = Arrays.stream(array).collect(Collectors.toList());\n return this.updateBatch(objList);\n }\n\n @Override\n public List<T> updateBatch(Collection<T> list) {\n super.updateBatchById(list);\n return new ArrayList<>(list);\n }\n\n @Override\n public int delete(Serializable id) {\n return mapper.deleteById(id);\n }\n\n @Override\n public int deleteBatch(Serializable[] ids) {\n List<Serializable> idList = Arrays.stream(ids).collect(Collectors.toList());\n return this.deleteBatch(idList);\n }\n\n @Override\n public int deleteBatch(Collection<? extends Serializable> ids) {\n return mapper.deleteBatchIds(ids);\n }\n\n @Override\n public int deleteByField(String field, Object value) {\n return mapper.delete(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public int deleteBatchByField(String field, Object[] values) {\n return mapper.delete(new QueryWrapper<T>().in(field, values));\n }\n\n @Override\n public int deleteBatchByField(String field, List<Object> values) {\n return this.deleteBatchByField(field, values.toArray());\n }\n\n @Override\n public T getById(Serializable id) {\n return mapper.selectById(id);\n }\n\n @Override\n public List<T> getByIds(Serializable[] ids) {\n List<Serializable> idList = Arrays.stream(ids).collect(Collectors.toList());\n return this.getByIds(idList);\n }\n\n @Override\n public List<T> getByIds(Collection<? extends Serializable> ids) {\n return mapper.selectBatchIds(ids);\n }\n\n @Override\n public List<T> getAll() {\n return super.list();\n }\n\n @Override\n public List<T> getByWrapper(Wrapper<T> wrapper) {\n return mapper.selectList(wrapper);\n }\n\n @Override\n public List<T> getByField(String field, Object value) {\n return mapper.selectList(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public List<T> getBatchByField(String field, Object[] values) {\n return mapper.selectList(new QueryWrapper<T>().in(field, values));\n }\n\n @Override\n public List<T> getBatchByField(String field, List<Object> values) {\n return this.getBatchByField(field, values.toArray());\n }\n\n @Override\n public List<T> getByObj(T obj) {\n if (ObjectUtil.isEmpty(obj)) {\n return getAll();\n }\n Map<String, Object> bean2Map = BeanUtil.beanToMap(obj);\n return getByMap(bean2Map);\n }\n\n @Override\n public List<T> getByMap(Map<String, Object> map) {\n Map<String, Object> newMap = new HashMap<>();\n for (String key : map.keySet()) {\n if (ObjectUtil.isEmpty(map.get(key))) {\n continue;\n }\n newMap.put(VariableNameUtils.humpToLine(key), map.get(key));\n }\n return mapper.selectByMap(newMap);\n }\n\n @Override\n public int countAll() {\n return super.count();\n }\n\n @Override\n public int countByField(String field, Object value) {\n return mapper.selectCount(new QueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public int countByWrapper(Wrapper<T> wrapper) {\n return mapper.selectCount(wrapper);\n }\n\n @Override\n public int countByObj(T obj) {\n return this.countByMap(BeanUtil.beanToMap(obj));\n }\n\n @Override\n public int countByMap(Map<String, Object> map) {\n return mapper.selectCount(createWrapperFromMap(map));\n }\n\n @Override\n public IPage<T> getByWrapperPage(Wrapper<T> wrapper, IPage<T> page) {\n return mapper.selectPage(page, wrapper);\n }\n\n @Override\n public IPage<T> getByObjPage(T obj, IPage<T> page) {\n return this.getByMapPage(BeanUtil.beanToMap(obj), page);\n }\n\n @Override\n public IPage<T> getByMapPage(Map<String, Object> map, IPage<T> page) {\n return this.getByWrapperPage(createWrapperFromMap(map), page);\n }\n\n /**\n * 通过 Map 创建 QueryWrapper 查询对象\n *\n * @param map 映射\n * @return QueryWrapper\n */\n private QueryWrapper<T> createWrapperFromMap(Map<String, Object> map) {\n QueryWrapper<T> wrapper = new QueryWrapper<>();\n for (Map.Entry<String, Object> temp : map.entrySet()) {\n String key = temp.getKey();\n if (ObjectUtil.isEmpty(temp.getValue())) {\n continue;\n }\n wrapper.eq(VariableNameUtils.humpToLine(key), map.get(key));\n }\n return wrapper;\n }\n}" }, { "identifier": "RespResult", "path": "xw-fast-web/src/main/java/world/xuewei/fast/web/dto/response/RespResult.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class RespResult {\n\n /**\n * 响应编码\n */\n protected String code;\n\n /**\n * 响应信息\n */\n protected String message;\n\n /**\n * 响应数据\n */\n protected Object data;\n\n /**\n * 请求成功\n */\n public static RespResult success() {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(\"请求成功\")\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message, Object data) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .data(data)\n .build();\n }\n\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound() {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(\"请求资源不存在\")\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(String.format(\"%s不存在\", message))\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message, Object data) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(String.format(\"%s不存在\", message))\n .data(data)\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty() {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(\"请求参数为空\")\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty(String message) {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(String.format(\"%s参数为空\", message))\n .build();\n }\n\n /**\n * 请求参数不能为空\n */\n public static RespResult paramEmpty(String message, Object data) {\n return RespResult.builder()\n .code(\"PARAM_EMPTY\")\n .message(String.format(\"%s参数为空\", message))\n .data(data)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail() {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(\"请求失败\")\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message, Object data) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .data(data)\n .build();\n }\n\n /**\n * 请求是否成功\n */\n public boolean yesSuccess() {\n return \"SUCCESS\".equals(code);\n }\n\n /**\n * 请求是否成功并有数据返回\n */\n public boolean yesSuccessWithDateResp() {\n return \"SUCCESS\".equals(code) && ObjectUtil.isNotEmpty(data);\n }\n\n /**\n * 请求是否成功\n */\n public boolean notSuccess() {\n return !yesSuccess();\n }\n}" } ]
import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import world.xuewei.fast.core.exception.BusinessRunTimeException; import world.xuewei.fast.core.exception.ParamEmptyException; import world.xuewei.fast.crud.dto.request.ReqBody; import world.xuewei.fast.crud.query.QueryBody; import world.xuewei.fast.crud.query.ResultPage; import world.xuewei.fast.crud.service.BaseDBService; import world.xuewei.fast.web.dto.response.RespResult; import java.io.Serializable; import java.util.List;
7,159
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody public RespResult saveData(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("新增成功", baseService.saveData(obj)); } /** * 批量保存实体 * * @param reqBody 通用请求体 * @return 实体对象列表 */ @PostMapping("/saveBatchData") @ResponseBody public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) { List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]")); return RespResult.success("新增成功", baseService.saveBatchData(objs)); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/delete") @ResponseBody public RespResult delete(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); int deleted = baseService.delete(id); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteBatch") @ResponseBody public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); int deleted = baseService.deleteBatch(ids); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteByField") @ResponseBody public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); int deleted = baseService.deleteByField(field, value); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/deleteBatchByField") @ResponseBody public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); int deleted = baseService.deleteBatchByField(field, values); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getById") @ResponseBody public RespResult getById(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); T t = baseService.getById(id); return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByIds") @ResponseBody public RespResult getByIds(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); return RespResult.success("查询成功", baseService.getByIds(ids)); } /** * 通过实体查询数据集合 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByObj") @ResponseBody public RespResult getByObj(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("查询成功", baseService.getByObj(obj)); } /** * 通过指定字段和值查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByField") @ResponseBody public RespResult getByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); return RespResult.success("查询成功", baseService.getByField(field, value)); } /** * 通过指定字段及对应值查询数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getBatchByField") @ResponseBody public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); return RespResult.success("查询成功", baseService.getBatchByField(field, values)); } /** * 查询全部 * * @return 出参 */ @PostMapping("/getAll") @ResponseBody public RespResult getAll() { return RespResult.success("查询成功", baseService.getAll()); } /** * 自定义查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/customQuery") @ResponseBody public RespResult customQuery(@RequestBody ReqBody<T> reqBody) { QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]")); // 参数合法性检查 queryBody.check(); QueryWrapper<T> queryWrapper = queryBody.buildWrapper(); IPage<T> page = queryBody.buildPage(); try { if (ObjectUtil.isNotEmpty(page)) { IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page);
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody public RespResult saveData(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("新增成功", baseService.saveData(obj)); } /** * 批量保存实体 * * @param reqBody 通用请求体 * @return 实体对象列表 */ @PostMapping("/saveBatchData") @ResponseBody public RespResult saveBatchData(@RequestBody ReqBody<T> reqBody) { List<T> objs = Assert.notEmpty(reqBody.getObjs(), () -> ParamEmptyException.build("实体数组[objs]")); return RespResult.success("新增成功", baseService.saveBatchData(objs)); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/delete") @ResponseBody public RespResult delete(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); int deleted = baseService.delete(id); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteBatch") @ResponseBody public RespResult deleteBatch(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); int deleted = baseService.deleteBatch(ids); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 删除条数 */ @PostMapping("/deleteByField") @ResponseBody public RespResult deleteByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); int deleted = baseService.deleteByField(field, value); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过指定字段及对应值删除数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/deleteBatchByField") @ResponseBody public RespResult deleteBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); int deleted = baseService.deleteBatchByField(field, values); return deleted == 0 ? RespResult.notFound("目标") : RespResult.success("删除成功", deleted); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getById") @ResponseBody public RespResult getById(@RequestBody ReqBody<T> reqBody) { Serializable id = Assert.notNull(reqBody.getId(), () -> ParamEmptyException.build("ID[id]")); T t = baseService.getById(id); return ObjectUtil.isEmpty(t) ? RespResult.notFound("目标") : RespResult.success("查询成功", t); } /** * 通过主键查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByIds") @ResponseBody public RespResult getByIds(@RequestBody ReqBody<T> reqBody) { List<Serializable> ids = Assert.notEmpty(reqBody.getIds(), () -> ParamEmptyException.build("ID数组[ids]")); return RespResult.success("查询成功", baseService.getByIds(ids)); } /** * 通过实体查询数据集合 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByObj") @ResponseBody public RespResult getByObj(@RequestBody ReqBody<T> reqBody) { T obj = Assert.notNull(reqBody.getObj(), () -> ParamEmptyException.build("实体[obj]")); return RespResult.success("查询成功", baseService.getByObj(obj)); } /** * 通过指定字段和值查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getByField") @ResponseBody public RespResult getByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); Object value = Assert.notNull(reqBody.getValue(), () -> ParamEmptyException.build("值[value]")); return RespResult.success("查询成功", baseService.getByField(field, value)); } /** * 通过指定字段及对应值查询数据 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/getBatchByField") @ResponseBody public RespResult getBatchByField(@RequestBody ReqBody<T> reqBody) { String field = Assert.notNull(reqBody.getField(), () -> ParamEmptyException.build("字段[field]")); List<Object> values = Assert.notEmpty(reqBody.getValues(), () -> ParamEmptyException.build("值数组[values]")); return RespResult.success("查询成功", baseService.getBatchByField(field, values)); } /** * 查询全部 * * @return 出参 */ @PostMapping("/getAll") @ResponseBody public RespResult getAll() { return RespResult.success("查询成功", baseService.getAll()); } /** * 自定义查询 * * @param reqBody 通用请求体 * @return 出参 */ @PostMapping("/customQuery") @ResponseBody public RespResult customQuery(@RequestBody ReqBody<T> reqBody) { QueryBody<T> queryBody = Assert.notNull(reqBody.getQueryBody(), () -> ParamEmptyException.build("查询策略[queryBody]")); // 参数合法性检查 queryBody.check(); QueryWrapper<T> queryWrapper = queryBody.buildWrapper(); IPage<T> page = queryBody.buildPage(); try { if (ObjectUtil.isNotEmpty(page)) { IPage<T> wrapperPage = baseService.getByWrapperPage(queryWrapper, page);
ResultPage<T> resultPage = new ResultPage<>(wrapperPage);
4
2023-11-07 11:45:40+00:00
8k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/activities/auth/signup/SignUpActivity.java
[ { "identifier": "UserDAO", "path": "app/src/main/java/com/daominh/quickmem/data/dao/UserDAO.java", "snippet": "public class UserDAO {\n\n private final QMDatabaseHelper qmDatabaseHelper;\n private SQLiteDatabase sqLiteDatabase;\n\n public UserDAO(Context context) {\n qmDatabaseHelper = new QMDatabaseHelper(context);\n }\n\n //insert user\n public long insertUser(User user) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"id\", user.getId());\n contentValues.put(\"name\", user.getName());\n contentValues.put(\"email\", user.getEmail());\n contentValues.put(\"username\", user.getUsername());\n contentValues.put(\"password\", user.getPassword());\n contentValues.put(\"avatar\", user.getAvatar());\n contentValues.put(\"role\", user.getRole());\n contentValues.put(\"created_at\", user.getCreated_at());\n contentValues.put(\"updated_at\", user.getUpdated_at());\n contentValues.put(\"status\", user.getStatus());\n\n try {\n return sqLiteDatabase.insert(QMDatabaseHelper.TABLE_USERS, null, contentValues);\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"insertUser: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check email is exist\n public boolean checkEmail(String email) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + email + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkEmail: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check username exists\n public boolean checkUsername(String username) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE username = '\" + username + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkUsername: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //check if username is existed\n\n //check password with email\n public boolean checkPasswordEmail(String email, String password) {\n return checkPassword(email, password);\n }\n\n //check password with username\n public boolean checkPasswordUsername(String username, String password) {\n return checkPassword(username, password);\n }\n\n private boolean checkPassword(String identifier, String password) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n password = PasswordHasher.hashPassword(password);\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + identifier + \"' OR username = '\" + identifier + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n int passwordIndex = cursor.getColumnIndex(\"password\");\n if (passwordIndex != -1) {\n String hashedPassword = cursor.getString(passwordIndex);\n assert password != null;\n return password.equals(hashedPassword);\n }\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkPassword: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return false;\n }\n\n //get user by email not contain password\n public User getUserByEmail(String email) {\n return getUserByIdentifier(email);\n }\n\n //get email by username\n public String getEmailByUsername(String username) {\n User user = getUserByIdentifier(username);\n return user != null ? user.getEmail() : null;\n }\n\n @SuppressLint(\"Range\")\n private User getUserByIdentifier(String identifier) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE email = '\" + identifier + \"' OR username = '\" + identifier + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n return new User(id, name, email, username, null, avatar, role, created_at, updated_at, status);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserByIdentifier: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //get password by id user\n @SuppressLint(\"Range\")\n public String getPasswordUser(String id) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n return cursor.getString(cursor.getColumnIndex(\"password\"));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getPasswordUser: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //update status user by id\n public long updateUser(String id, ContentValues contentValues) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n\n try {\n return sqLiteDatabase.update(QMDatabaseHelper.TABLE_USERS, contentValues, \"id = ?\", new String[]{id});\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"updateUser: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n //update email by id user\n public long updateEmailUser(String id, String email) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"email\", email);\n return updateUser(id, contentValues);\n }\n\n //update username by id user\n public long updateUsernameUser(String id, String username) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"username\", username);\n return updateUser(id, contentValues);\n }\n\n //update password by id user\n public long updatePasswordUser(String id, String password) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"password\", password);\n return updateUser(id, contentValues);\n }\n\n //update status by id user\n public void updateStatusUser(String id, int status) {\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"status\", status);\n updateUser(id, contentValues);\n }\n\n @SuppressLint(\"Range\")\n //get all user to not contain password\n public ArrayList<User> getAllUser() {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS;\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n users.add(new User(id, name, email, username, null, avatar, role, created_at, updated_at, status));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getAllUser: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return users;\n }\n\n @SuppressLint(\"Range\")\n //get user by id not contain password\n public User getUserById(String id) {\n\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n String email = cursor.getString(cursor.getColumnIndex(\"email\"));\n String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n int role = cursor.getInt(cursor.getColumnIndex(\"role\"));\n String created_at = cursor.getString(cursor.getColumnIndex(\"created_at\"));\n String updated_at = cursor.getString(cursor.getColumnIndex(\"updated_at\"));\n int status = cursor.getInt(cursor.getColumnIndex(\"status\"));\n\n return new User(id, name, email, username, null, avatar, role, created_at, updated_at, status);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserById: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n //get list user by id class just need id, username, avatar\n public ArrayList<User> getListUserByIdClass(String idClass) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id IN (SELECT user_id FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE class_id = '\" + idClass + \"')\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n @SuppressLint(\"Range\") String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n\n users.add(new User(id, null, null, username, null, avatar, 0, null, null, 0));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getListUserByIdClass: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return users;\n }\n\n //get all user just need id, username, avatar\n public ArrayList<User> getAllUserJustNeed() {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n ArrayList<User> users = new ArrayList<>();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS;\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n while (cursor.moveToNext()) {\n @SuppressLint(\"Range\") String id = cursor.getString(cursor.getColumnIndex(\"id\"));\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n Log.e(\"UserDAO\", \"getAllUserJustNeed: \" + id + \" \" + username + \" \" + avatar);\n\n users.add(new User(id, null, null, username, null, avatar, 0, null, null, 0));\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getAllUserJustNeed: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n for (User user : users) {\n if (user.getUsername().equals(\"admin\")) {\n users.remove(user);\n break;\n }\n\n }\n return users;\n }\n\n //get user by id class just need username, avatar by id\n public User getUserByIdClass(String id) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_USERS + \" WHERE id = '\" + id + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n @SuppressLint(\"Range\") String username = cursor.getString(cursor.getColumnIndex(\"username\"));\n @SuppressLint(\"Range\") String avatar = cursor.getString(cursor.getColumnIndex(\"avatar\"));\n\n return new User(id, null, null, username, null, avatar, 0, null, null, 0);\n }\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"getUserByIdClass: \" + e);\n } finally {\n sqLiteDatabase.close();\n }\n return null;\n }\n\n // check if user is in class\n public boolean checkUserInClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getReadableDatabase();\n String query = \"SELECT * FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE user_id = '\" + userId + \"' AND class_id = '\" + classId + \"'\";\n\n try (Cursor cursor = sqLiteDatabase.rawQuery(query, null)) {\n return cursor.getCount() > 0;\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"checkUserInClass: \" + e);\n return false;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n // remove user from class\n public long removeUserFromClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n String query = \"DELETE FROM \" + QMDatabaseHelper.TABLE_CLASSES_USERS + \" WHERE user_id = '\" + userId + \"' AND class_id = '\" + classId + \"'\";\n\n try {\n return sqLiteDatabase.delete(QMDatabaseHelper.TABLE_CLASSES_USERS, \"user_id = ? AND class_id = ?\", new String[]{userId, classId});\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"removeUserFromClass: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n // add user to class\n public long addUserToClass(String userId, String classId) {\n sqLiteDatabase = qmDatabaseHelper.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"user_id\", userId);\n contentValues.put(\"class_id\", classId);\n\n try {\n return sqLiteDatabase.insert(QMDatabaseHelper.TABLE_CLASSES_USERS, null, contentValues);\n } catch (SQLException e) {\n Log.e(\"UserDAO\", \"addUserToClass: \" + e);\n return 0;\n } finally {\n sqLiteDatabase.close();\n }\n }\n\n}" }, { "identifier": "User", "path": "app/src/main/java/com/daominh/quickmem/data/model/User.java", "snippet": "public class User {\n private String id;\n private String name;\n private String email;\n private String username;\n private String password;\n private String avatar;\n private int role;\n private String created_at;\n private String updated_at;\n private int status;\n\n public User() {\n }\n\n public User(String id, String name, String email, String username, String password, String avatar, int role, String created_at, String updated_at, int status) {\n this.id = id;\n this.name = name;\n this.email = email;\n this.username = username;\n this.password = password;\n this.avatar = avatar;\n this.role = role;\n this.created_at = created_at;\n this.updated_at = updated_at;\n this.status = status;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public int getRole() {\n return role;\n }\n\n public void setRole(int role) {\n this.role = role;\n }\n\n public String getCreated_at() {\n return created_at;\n }\n\n public void setCreated_at(String created_at) {\n this.created_at = created_at;\n }\n\n public String getUpdated_at() {\n return updated_at;\n }\n\n public void setUpdated_at(String updated_at) {\n this.updated_at = updated_at;\n }\n\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n}" }, { "identifier": "UserSharePreferences", "path": "app/src/main/java/com/daominh/quickmem/preferen/UserSharePreferences.java", "snippet": "public class UserSharePreferences {\n\n //create variables\n public static final String KEY_LOGIN = \"login\";\n public static final String KEY_ID = \"id\";\n private static final String KEY_AVATAR = \"avatar\";\n private static final String KEY_USER_NAME = \"user_name\";\n private static final String KEY_ROLE = \"role_user\";\n private static final String KEY_STATUS = \"status\";\n private static final String KEY_EMAIL = \"email\";\n public static final String KEY_CLASS_ID = \"class_id\";\n\n private final SharedPreferences sharedPreferences;\n\n public UserSharePreferences(Context context) {\n sharedPreferences = context.getSharedPreferences(\"user\", Context.MODE_PRIVATE);\n }\n\n //set login\n public void setLogin(boolean login) {\n sharedPreferences.edit().putBoolean(KEY_LOGIN, login).apply();\n }\n\n //get login\n public boolean getLogin() {\n return sharedPreferences.getBoolean(KEY_LOGIN, false);\n }\n\n //set id\n public void setId(String id) {\n sharedPreferences.edit().putString(KEY_ID, id).apply();\n }\n\n //get id\n public String getId() {\n return sharedPreferences.getString(KEY_ID, \"\");\n }\n\n // get, set role user\n public void setRole(int role) {\n sharedPreferences.edit().putInt(KEY_ROLE, role).apply();\n }\n\n //get role user\n public int getRole() {\n return sharedPreferences.getInt(KEY_ROLE, -1);\n }\n\n //set,get status\n public void setStatus(int status) {\n sharedPreferences.edit().putInt(KEY_STATUS, status).apply();\n }\n\n //get status\n public int getStatus() {\n return sharedPreferences.getInt(KEY_STATUS, -1);\n }\n\n //set avatar\n public void setAvatar(String avatar) {\n sharedPreferences.edit().putString(KEY_AVATAR, avatar).apply();\n }\n\n //get avatar\n public String getAvatar() {\n return sharedPreferences.getString(KEY_AVATAR, \"\");\n }\n\n //set username\n public void setUserName(String userName) {\n sharedPreferences.edit().putString(KEY_USER_NAME, userName).apply();\n }\n\n //get username\n public String getUserName() {\n return sharedPreferences.getString(KEY_USER_NAME, \"\");\n }\n\n //set email\n public void setEmail(String email) {\n sharedPreferences.edit().putString(KEY_EMAIL, email).apply();\n }\n\n //get email\n public String getEmail() {\n return sharedPreferences.getString(KEY_EMAIL, \"\");\n }\n\n //set class id\n public void setClassId(String classId) {\n sharedPreferences.edit().putString(KEY_CLASS_ID, classId).apply();\n }\n\n //get class id\n public String getClassId() {\n return sharedPreferences.getString(KEY_CLASS_ID, \"\");\n }\n\n //remove class id\n public void removeClassId() {\n sharedPreferences.edit().remove(KEY_CLASS_ID).apply();\n }\n\n //set user\n public void saveUser(User user) {\n setId(user.getId());\n setUserName(user.getUsername());\n setEmail(user.getEmail());\n setAvatar(user.getAvatar());\n setRole(user.getRole());\n setStatus(user.getStatus());\n setLogin(true);\n }\n\n //clear\n public void clear() {\n sharedPreferences.edit().clear().apply();\n }\n}" }, { "identifier": "MainActivity", "path": "app/src/main/java/com/daominh/quickmem/ui/activities/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n private NavController navController;\n private ActivityMainBinding binding;\n\n UserSharePreferences userSharePreferences;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n View view = binding.getRoot();\n setContentView(view);\n setupNavigation();\n\n }\n\n private void setupNavigation() {\n\n userSharePreferences = new UserSharePreferences(MainActivity.this);\n int role = userSharePreferences.getRole();\n\n navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);\n\n int navGraphId;\n int menuId;\n\n if (role == 0) {\n navGraphId = R.navigation.main_nav_admin;\n menuId = R.menu.menu_nav_admin;\n } else {\n navGraphId = R.navigation.main_nav;\n menuId = R.menu.menu_nav;\n }\n\n navController.setGraph(navGraphId);\n binding.bottomNavigationView.getMenu().clear();\n binding.bottomNavigationView.inflateMenu(menuId);\n\n NavigationUI.setupWithNavController(binding.bottomNavigationView, navController);\n }\n\n @Override\n public boolean onSupportNavigateUp() {\n return navController.navigateUp() || super.onSupportNavigateUp();\n }\n}" }, { "identifier": "AuthenticationActivity", "path": "app/src/main/java/com/daominh/quickmem/ui/activities/auth/AuthenticationActivity.java", "snippet": "public class AuthenticationActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n UserSharePreferences userSharePreferences = new UserSharePreferences(this);\n\n // Assuming that userSharePreferences is initialized somewhere else\n if (userSharePreferences.getLogin()) {\n startActivity(new Intent(this, MainActivity.class));\n finish();\n }\n\n // Inflate the layout\n ActivityAuthenticationBinding binding = ActivityAuthenticationBinding.inflate(getLayoutInflater());\n final View view = binding.getRoot();\n setContentView(view);\n\n // Setup onboarding\n OnboardingAdapter onboardingAdapter = new OnboardingAdapter(this);\n binding.onboardingVp.setAdapter(onboardingAdapter);\n binding.indicator.setViewPager(binding.onboardingVp);\n\n // Setup sign up button\n binding.signUpBtn.setOnClickListener(v -> {\n startActivity(new Intent(this, SignUpActivity.class));\n finish();\n });\n\n // Setup sign in button\n binding.signInBtn.setOnClickListener(v -> {\n startActivity(new Intent(this, SignInActivity.class));\n finish();\n });\n }\n}" }, { "identifier": "PasswordHasher", "path": "app/src/main/java/com/daominh/quickmem/utils/PasswordHasher.java", "snippet": "public class PasswordHasher {\n public static String hashPassword(String password) {\n try {\n // Create MessageDigest instance for SHA-256\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n\n // Add password bytes to digest\n md.update(password.getBytes());\n\n // Get the hash's bytes\n byte[] bytes = md.digest();\n\n // These bytes[] has bytes in decimal format;\n // Convert it to hexadecimal format\n StringBuilder sb = new StringBuilder();\n for (byte aByte : bytes) {\n sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));\n }\n\n // Get complete hashed password in hexadecimal format\n return sb.toString();\n } catch (NoSuchAlgorithmException e) {\n Log.e(\"PasswordHasher\", \"Error hashing password\", e);\n }\n return null;\n }\n\n // check password\n public static boolean checkPassword(String password, String hashedPassword) {\n // Hash the plain text password\n String hashOfInput = hashPassword(password);\n Log.d(\"PasswordHasher\", \"checkPassword: \" + hashOfInput);\n\n // Compare the hashed password with the hash of the input password\n return hashOfInput != null && hashOfInput.equals(hashedPassword);\n }\n}" } ]
import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Color; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Toast; import androidx.activity.OnBackPressedCallback; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.appcompat.content.res.AppCompatResources; import com.daominh.quickmem.R; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.data.model.User; import com.daominh.quickmem.databinding.ActivitySignupBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.MainActivity; import com.daominh.quickmem.ui.activities.auth.AuthenticationActivity; import com.daominh.quickmem.utils.PasswordHasher; import com.swnishan.materialdatetimepicker.datepicker.MaterialDatePickerDialog; import com.swnishan.materialdatetimepicker.datepicker.MaterialDatePickerView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.UUID;
7,004
package com.daominh.quickmem.ui.activities.auth.signup; public class SignUpActivity extends AppCompatActivity { private UserDAO userDAO; private static final int MAX_LENGTH = 30; private static final String link = "https://avatar-nqm.koyeb.app/images"; ActivitySignupBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySignupBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); setSupportActionBar(binding.toolbar); setupToolbar(); setupSocialLoginButtons(); setupDateEditText(); setupEmailEditText(); setupPasswordEditText(); setupSignUpButton(); setupOnBackPressedCallback(); } private void setupToolbar() { binding.toolbar.setNavigationOnClickListener(v -> { startActivity(new Intent(this, AuthenticationActivity.class)); finish(); }); } private void setupSocialLoginButtons() { binding.facebookBtn.setOnClickListener(v -> { // intentToMain(); }); binding.googleBtn.setOnClickListener(v -> { // intentToMain(); }); } private void setupDateEditText() { binding.dateEt.setOnClickListener(v -> openDialogDatePicker(binding.dateEt::setText)); binding.dateEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handleDateTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handleDateTextChanged(s.toString(), binding); } }); } private void setupEmailEditText() { binding.emailEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handleEmailTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handleEmailTextChanged(s.toString(), binding); } }); } private void setupPasswordEditText() { binding.passwordEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handlePasswordTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handlePasswordTextChanged(s.toString(), binding); } }); } private void setupSignUpButton() { binding.signUpBtn.setOnClickListener(v -> { final String date = binding.dateEt.getText().toString(); final String email = binding.emailEt.getText().toString(); final String password = binding.passwordEt.getText().toString(); if (!handleDateTextChanged(date, binding)) return; if (!handleEmailTextChanged(email, binding)) return; if (!handlePasswordTextChanged(password, binding)) return; int role = 2; if (binding.radioYesNo.getCheckedRadioButtonId() == binding.radioYes.getId()) { role = 1; } handleSignUp(date, email, password, role); }); } private void handleSignUp(String date, String email, String password, int role) { // Create a new User object User newUser = new User(); newUser.setId(UUID.randomUUID().toString()); newUser.setEmail(email); newUser.setAvatar(randomAvatar()); newUser.setName(""); newUser.setUsername(userNameFromEmail(email)); newUser.setRole(role);
package com.daominh.quickmem.ui.activities.auth.signup; public class SignUpActivity extends AppCompatActivity { private UserDAO userDAO; private static final int MAX_LENGTH = 30; private static final String link = "https://avatar-nqm.koyeb.app/images"; ActivitySignupBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySignupBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); setSupportActionBar(binding.toolbar); setupToolbar(); setupSocialLoginButtons(); setupDateEditText(); setupEmailEditText(); setupPasswordEditText(); setupSignUpButton(); setupOnBackPressedCallback(); } private void setupToolbar() { binding.toolbar.setNavigationOnClickListener(v -> { startActivity(new Intent(this, AuthenticationActivity.class)); finish(); }); } private void setupSocialLoginButtons() { binding.facebookBtn.setOnClickListener(v -> { // intentToMain(); }); binding.googleBtn.setOnClickListener(v -> { // intentToMain(); }); } private void setupDateEditText() { binding.dateEt.setOnClickListener(v -> openDialogDatePicker(binding.dateEt::setText)); binding.dateEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handleDateTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handleDateTextChanged(s.toString(), binding); } }); } private void setupEmailEditText() { binding.emailEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handleEmailTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handleEmailTextChanged(s.toString(), binding); } }); } private void setupPasswordEditText() { binding.passwordEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handlePasswordTextChanged(s.toString(), binding); } @Override public void afterTextChanged(Editable s) { handlePasswordTextChanged(s.toString(), binding); } }); } private void setupSignUpButton() { binding.signUpBtn.setOnClickListener(v -> { final String date = binding.dateEt.getText().toString(); final String email = binding.emailEt.getText().toString(); final String password = binding.passwordEt.getText().toString(); if (!handleDateTextChanged(date, binding)) return; if (!handleEmailTextChanged(email, binding)) return; if (!handlePasswordTextChanged(password, binding)) return; int role = 2; if (binding.radioYesNo.getCheckedRadioButtonId() == binding.radioYes.getId()) { role = 1; } handleSignUp(date, email, password, role); }); } private void handleSignUp(String date, String email, String password, int role) { // Create a new User object User newUser = new User(); newUser.setId(UUID.randomUUID().toString()); newUser.setEmail(email); newUser.setAvatar(randomAvatar()); newUser.setName(""); newUser.setUsername(userNameFromEmail(email)); newUser.setRole(role);
newUser.setPassword(PasswordHasher.hashPassword(password));
5
2023-11-07 16:56:39+00:00
8k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/Robot.java
[ { "identifier": "RobotIdentity", "path": "src/main/java/org/frcteam2910/c2023/config/RobotIdentity.java", "snippet": "public enum RobotIdentity {\n LOKI_2023_ONE,\n PHANTOM_2023_TWO,\n ROBOT_2022,\n SIMULATION;\n\n public static RobotIdentity getIdentity() {\n if (Robot.isReal()) {\n String mac = getMACAddress();\n if (!mac.equals(\"\")) {\n if (mac.equals(MacAddressUtil.ROBOT_ONE_MAC) || mac.equals(SECONDARY_ROBOT_ONE_MAC)) {\n return LOKI_2023_ONE;\n } else if (mac.equals(MacAddressUtil.ROBOT_TWO_MAC)) {\n return PHANTOM_2023_TWO;\n }\n }\n if (Constants.COMPETITION_ROBOT == LOKI_2023_ONE) {\n return LOKI_2023_ONE;\n } else {\n return PHANTOM_2023_TWO;\n }\n } else {\n return SIMULATION;\n }\n }\n}" }, { "identifier": "LEDSubsystem", "path": "src/main/java/org/frcteam2910/c2023/subsystems/led/LEDSubsystem.java", "snippet": "public class LEDSubsystem extends SubsystemBase {\n public enum WantedAction {\n DISPLAY_LOW_BATTERY,\n DISPLAY_ROBOT_ZEROED,\n DISPLAY_ROBOT_NOT_ZEROED,\n DISPLAY_ROBOT_ARM_ZEROED,\n DISPLAY_ROBOT_ARM_NOT_ZEROED,\n DISPLAY_INITIALIZE,\n DISPLAY_GETTING_CUBE,\n DISPLAY_GETTING_CONE,\n DISPLAY_GETTING_CUBE_FLASHING,\n DISPLAY_GETTING_CONE_FLASHING,\n DISPLAY_GETTING_CUBE_FLASHING_WHITE,\n DISPLAY_GETTING_CONE_FLASHING_WHITE,\n DISPLAY_LIMELIGHT_MIMICRY,\n DISPLAY_IS_DOING_CHARGING_STATION,\n DISPLAY_SUPERSTRUCTURE,\n DISPLAY_OFF,\n DISPLAY_ALIGN_BAD\n }\n\n private enum SystemState {\n DISPLAYING_LOW_BATTERY,\n DISPLAYING_ROBOT_ZEROED,\n DISPLAYING_ROBOT_NOT_ZEROED,\n DISPLAYING_ROBOT_ARM_ZEROED,\n DISPLAYING_ROBOT_ARM_NOT_ZEROED,\n DISPLAYING_INITIALIZE,\n DISPLAYING_GETTING_CUBE,\n DISPLAYING_GETTING_CONE,\n DISPLAYING_GETTING_CUBE_FLASHING,\n DISPLAYING_GETTING_CONE_FLASHING,\n DISPLAYING_GETTING_CUBE_FLASHING_WHITE,\n DISPLAYING_GETTING_CONE_FLASHING_WHITE,\n DISPLAYING_LIMELIGHT_MIMICRY,\n DISPLAYING_IS_DOING_CHARGING_STATION,\n DISPLAYING_SUPERSTRUCTURE,\n DISPLAYING_OFF,\n DISPLAYING_ALIGN_BAD\n }\n\n private double stateStartTime;\n private SystemState systemState = SystemState.DISPLAYING_SUPERSTRUCTURE;\n private WantedAction wantedAction = WantedAction.DISPLAY_SUPERSTRUCTURE;\n private LEDState desiredLEDState = new LEDState(0, 0, 0);\n private final LEDTimedState superstructureLEDState = LEDTimedState.StaticLEDState.staticOff;\n private final LEDIO ledIO;\n\n private void setZeroedCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.ROBOT_ZEROING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setNotZeroedCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.ROBOT_NOT_ZEROING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setLowBatteryCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.BATTERY_LOW.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setSuperstructureLEDCommand(double timeInState) {\n superstructureLEDState.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setInitializeCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.INITIALIZING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setConeCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CONE.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setCubeCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CUBE.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setConeFlashingCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CONE_FLASHING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setCubeFlashingCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CUBE_FLASHING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setConeFlashingWhiteCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CONE_FLASHING_WHITE.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setCubeFlashingWhiteCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.GETTING_CUBE_FLASHING_WHITE.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setArmZeroedCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.ARM_ZEROING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setArmNotZeroedCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.ARM_NOT_ZEROING.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setLimelightMimicryCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.LIMELIGHT_MIMICRY.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setClimbingCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.IS_DOING_CHARGING_STATION.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setOffCommand(double timeInState) {\n LEDTimedState.StaticLEDState.staticOff.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private void setAlignBadCommand(double timeInState) {\n LEDTimedState.BlinkingLEDState.ALIGN_BAD.getCurrentLEDState(desiredLEDState, timeInState);\n }\n\n private SystemState getStateTransition() {\n switch (wantedAction) {\n case DISPLAY_INITIALIZE:\n return SystemState.DISPLAYING_INITIALIZE;\n case DISPLAY_SUPERSTRUCTURE:\n return SystemState.DISPLAYING_SUPERSTRUCTURE;\n case DISPLAY_LOW_BATTERY:\n return SystemState.DISPLAYING_LOW_BATTERY;\n case DISPLAY_GETTING_CONE:\n return SystemState.DISPLAYING_GETTING_CONE;\n case DISPLAY_GETTING_CUBE:\n return SystemState.DISPLAYING_GETTING_CUBE;\n case DISPLAY_GETTING_CONE_FLASHING:\n return SystemState.DISPLAYING_GETTING_CONE_FLASHING;\n case DISPLAY_GETTING_CUBE_FLASHING:\n return SystemState.DISPLAYING_GETTING_CUBE_FLASHING;\n case DISPLAY_GETTING_CONE_FLASHING_WHITE:\n return SystemState.DISPLAYING_GETTING_CONE_FLASHING_WHITE;\n case DISPLAY_GETTING_CUBE_FLASHING_WHITE:\n return SystemState.DISPLAYING_GETTING_CUBE_FLASHING_WHITE;\n case DISPLAY_ROBOT_ZEROED:\n return SystemState.DISPLAYING_ROBOT_ZEROED;\n case DISPLAY_ROBOT_NOT_ZEROED:\n return SystemState.DISPLAYING_ROBOT_NOT_ZEROED;\n case DISPLAY_ROBOT_ARM_ZEROED:\n return SystemState.DISPLAYING_ROBOT_ARM_ZEROED;\n case DISPLAY_ROBOT_ARM_NOT_ZEROED:\n return SystemState.DISPLAYING_ROBOT_ARM_NOT_ZEROED;\n case DISPLAY_LIMELIGHT_MIMICRY:\n return SystemState.DISPLAYING_LIMELIGHT_MIMICRY;\n case DISPLAY_IS_DOING_CHARGING_STATION:\n return SystemState.DISPLAYING_IS_DOING_CHARGING_STATION;\n case DISPLAY_ALIGN_BAD:\n return SystemState.DISPLAYING_ALIGN_BAD;\n case DISPLAY_OFF:\n return SystemState.DISPLAYING_OFF;\n default:\n System.out.println(\"Fell through on LED wanted action check: \" + wantedAction);\n return SystemState.DISPLAYING_SUPERSTRUCTURE;\n }\n }\n\n public void setWantedAction(WantedAction wantedAction) {\n this.wantedAction = wantedAction;\n }\n\n private final LEDIO.LEDIOInputs ledioInputs = new LEDIO.LEDIOInputs();\n\n public LEDSubsystem(LEDIO ledIO) {\n this.ledIO = ledIO;\n }\n\n @Override\n public void periodic() {\n var timestamp = Timer.getFPGATimestamp();\n SystemState newState = getStateTransition();\n if (systemState != newState) {\n System.out.println(timestamp + \": LED changed states: \" + systemState + \" -> \" + newState);\n systemState = newState;\n stateStartTime = timestamp;\n }\n double timeInState = timestamp - stateStartTime;\n switch (systemState) {\n case DISPLAYING_SUPERSTRUCTURE:\n setSuperstructureLEDCommand(timeInState);\n break;\n case DISPLAYING_LOW_BATTERY:\n setLowBatteryCommand(timeInState);\n break;\n case DISPLAYING_ROBOT_ZEROED:\n setZeroedCommand(timeInState);\n break;\n case DISPLAYING_ROBOT_NOT_ZEROED:\n setNotZeroedCommand(timeInState);\n break;\n case DISPLAYING_ROBOT_ARM_ZEROED:\n setArmZeroedCommand(timeInState);\n break;\n case DISPLAYING_ROBOT_ARM_NOT_ZEROED:\n setArmNotZeroedCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CONE:\n setConeCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CUBE:\n setCubeCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CONE_FLASHING:\n setConeFlashingCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CUBE_FLASHING:\n setCubeFlashingCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CONE_FLASHING_WHITE:\n setConeFlashingWhiteCommand(timeInState);\n break;\n case DISPLAYING_GETTING_CUBE_FLASHING_WHITE:\n setCubeFlashingWhiteCommand(timeInState);\n break;\n case DISPLAYING_INITIALIZE:\n setInitializeCommand(timeInState);\n break;\n case DISPLAYING_LIMELIGHT_MIMICRY:\n setLimelightMimicryCommand(timeInState);\n break;\n case DISPLAYING_IS_DOING_CHARGING_STATION:\n setClimbingCommand(timeInState);\n break;\n case DISPLAYING_ALIGN_BAD:\n setAlignBadCommand(timeInState);\n break;\n case DISPLAYING_OFF:\n setOffCommand(timeInState);\n break;\n default:\n System.out.println(\"Fell through on LED commands: \" + systemState);\n break;\n }\n ledIO.updateInputs(ledioInputs, desiredLEDState.red, desiredLEDState.green, desiredLEDState.blue);\n ledIO.setLEDs(desiredLEDState.red, desiredLEDState.green, desiredLEDState.blue);\n }\n\n public WantedAction getWantedAction() {\n return wantedAction;\n }\n\n public boolean getIsBadAlign() {\n return wantedAction == WantedAction.DISPLAY_ALIGN_BAD;\n }\n\n public boolean getIsFlashing() {\n return wantedAction == WantedAction.DISPLAY_GETTING_CONE_FLASHING\n || wantedAction == WantedAction.DISPLAY_GETTING_CUBE_FLASHING\n || wantedAction == WantedAction.DISPLAY_GETTING_CONE_FLASHING_WHITE\n || wantedAction == WantedAction.DISPLAY_GETTING_CUBE_FLASHING_WHITE;\n }\n}" }, { "identifier": "DriverReadouts", "path": "src/main/java/org/frcteam2910/c2023/util/DriverReadouts.java", "snippet": "public class DriverReadouts {\n\n public DriverReadouts(RobotContainer container) {\n ShuffleboardTab tab = Shuffleboard.getTab(Constants.DRIVER_READOUTS_TAB_NAME);\n\n tab.add(\"Autonomous Mode\", PathChooser.getModeChooser()).withSize(5, 2).withPosition(9, 0);\n }\n}" }, { "identifier": "GamePiece", "path": "src/main/java/org/frcteam2910/c2023/util/GamePiece.java", "snippet": "public enum GamePiece {\n CONE,\n CUBE\n}" }, { "identifier": "MacAddressUtil", "path": "src/main/java/org/frcteam2910/c2023/util/MacAddressUtil.java", "snippet": "public class MacAddressUtil {\n public static final String ROBOT_ONE_MAC = \"00-80-2F-35-B9-60\";\n public static final String SECONDARY_ROBOT_ONE_MAC = \"10-50-FD-C6-35-0D\";\n public static final String ROBOT_TWO_MAC = \"92-9B-20-68-07-62\";\n\n public static String getMACAddress() {\n try {\n Enumeration<NetworkInterface> networkInterface = NetworkInterface.getNetworkInterfaces();\n StringBuilder macAddress = new StringBuilder();\n while (networkInterface.hasMoreElements()) {\n NetworkInterface tempInterface =\n networkInterface.nextElement(); // Instantiates the next element in our network interface\n if (tempInterface != null) {\n byte[] mac = tempInterface.getHardwareAddress(); // Reads the MAC address from our NetworkInterface\n if (mac != null) {\n for (int i = 0; i < mac.length; i++) {\n // Formats our mac address by splitting it into two-character segments and hyphenating them\n // (unless it is the final segment)\n macAddress.append(String.format(\"%02X%s\", mac[i], (i < mac.length - 1) ? \"-\" : \"\"));\n }\n return macAddress.toString();\n } else {\n System.out.println(\"Address not accessible\");\n }\n } else {\n System.out.println(\"Network Interface for the specified address not found\");\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return \"\";\n }\n}" }, { "identifier": "FieldConstants", "path": "src/main/java/org/frcteam2910/c2023/util/constants/FieldConstants.java", "snippet": "public class FieldConstants {\n public static final double FIELD_LENGTH_M = Units.feetToMeters(54.0);\n public static AprilTagFieldLayout BLUE_FIELD_LAYOUT;\n public static AprilTagFieldLayout RED_FIELD_LAYOUT;\n private static DriverStation.Alliance storedAlliance = DriverStation.Alliance.Invalid;\n\n static {\n try {\n BLUE_FIELD_LAYOUT = AprilTagFieldLayout.loadFromResource(AprilTagFields.k2023ChargedUp.m_resourceFile);\n BLUE_FIELD_LAYOUT.setOrigin(AprilTagFieldLayout.OriginPosition.kBlueAllianceWallRightSide);\n RED_FIELD_LAYOUT = AprilTagFieldLayout.loadFromResource(AprilTagFields.k2023ChargedUp.m_resourceFile);\n RED_FIELD_LAYOUT.setOrigin(AprilTagFieldLayout.OriginPosition.kRedAllianceWallRightSide);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static final double LOW_CONE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(6.28);\n public static final double MID_CONE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(8.42);\n public static final double HIGH_CONE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(25.45);\n\n public static final double LOW_CUBE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(7.14);\n public static final double MID_CUBE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(8.655);\n public static final double HIGH_CUBE_X_CENTER_FROM_APRILTAG = Units.inchesToMeters(28.54);\n\n public static final double MID_CONE_NODE_HEIGHT_METERS = Units.inchesToMeters(34.0);\n public static final double MID_CUBE_NODE_HEIGHT_METERS = Units.inchesToMeters(23.5);\n public static final double HIGH_CONE_NODE_HEIGHT_METERS = Units.inchesToMeters(46.0);\n public static final double HIGH_CUBE_NODE_HEIGHT_METERS = Units.inchesToMeters(35.5);\n\n public static final double Y_BETWEEN_COLUMNS_METERS = Units.inchesToMeters(22.0);\n\n public static double PORTAL_TAG_X;\n public static double PORTAL_TAG_Y;\n public static double LEFT_TAG_X;\n public static double LEFT_TAG_Y;\n public static double MIDDLE_TAG_X;\n public static double MIDDLE_TAG_Y;\n public static double RIGHT_TAG_X;\n public static double RIGHT_TAG_Y;\n\n public static Pose3d PORTAL;\n\n public static Pose3d[] COLUMN_ONE;\n public static Pose3d[] COLUMN_TWO;\n public static Pose3d[] COLUMN_THREE;\n public static Pose3d[] COLUMN_FOUR;\n public static Pose3d[] COLUMN_FIVE;\n public static Pose3d[] COLUMN_SIX;\n public static Pose3d[] COLUMN_SEVEN;\n public static Pose3d[] COLUMN_EIGHT;\n public static Pose3d[] COLUMN_NINE;\n\n public static final Pose3d[] CHARGING_STATION = {\n new Pose3d(Units.inchesToMeters(114.74), Units.inchesToMeters(155.39), 0.0, new Rotation3d()), // bottom left\n new Pose3d(Units.inchesToMeters(162.74), Units.inchesToMeters(155.39), 0.0, new Rotation3d()), // top left\n new Pose3d(Units.inchesToMeters(114.74), Units.inchesToMeters(59.39), 0.0, new Rotation3d()), // top right\n new Pose3d(Units.inchesToMeters(114.74), Units.inchesToMeters(59.39), 0.0, new Rotation3d()) // bottom right\n };\n\n public static final Pose3d[] LOADING_ZONE = {\n new Pose3d(Units.inchesToMeters(385.36), Units.inchesToMeters(312), 0.0, new Rotation3d()),\n new Pose3d(Units.inchesToMeters(385.36), Units.inchesToMeters(263.43), 0.0, new Rotation3d()),\n new Pose3d(Units.inchesToMeters(515.75), Units.inchesToMeters(263.43), 0.0, new Rotation3d()),\n new Pose3d(Units.inchesToMeters(515.75), Units.inchesToMeters(212.93), 0.0, new Rotation3d()),\n new Pose3d(Units.inchesToMeters(648), Units.inchesToMeters(212.93), 0.0, new Rotation3d()),\n new Pose3d(Units.inchesToMeters(648), Units.inchesToMeters(312), 0.0, new Rotation3d())\n };\n\n public static AprilTagFieldLayout getFieldLayout() {\n if (DriverStation.getAlliance() == DriverStation.Alliance.Blue) {\n return BLUE_FIELD_LAYOUT;\n } else {\n return RED_FIELD_LAYOUT;\n }\n }\n\n public static void update() {\n if (DriverStation.getAlliance() != storedAlliance) {\n storedAlliance = DriverStation.getAlliance();\n System.out.println(storedAlliance);\n\n PORTAL_TAG_X = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 5 : 4)\n .get()\n .getX();\n PORTAL_TAG_Y = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 5 : 4)\n .get()\n .getY();\n LEFT_TAG_X = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 1 : 6)\n .get()\n .getX();\n LEFT_TAG_Y = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 1 : 6)\n .get()\n .getY();\n MIDDLE_TAG_X = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 2 : 7)\n .get()\n .getX();\n MIDDLE_TAG_Y = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 2 : 7)\n .get()\n .getY();\n RIGHT_TAG_X = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 3 : 8)\n .get()\n .getX();\n RIGHT_TAG_Y = getFieldLayout()\n .getTagPose(storedAlliance == DriverStation.Alliance.Red ? 3 : 8)\n .get()\n .getY();\n\n PORTAL = new Pose3d(FieldConstants.PORTAL_TAG_X, FieldConstants.PORTAL_TAG_Y, 0.0, new Rotation3d());\n\n COLUMN_ONE = new Pose3d[] {\n new Pose3d(\n LEFT_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_TWO = new Pose3d[] {\n new Pose3d(LEFT_TAG_X + LOW_CUBE_X_CENTER_FROM_APRILTAG, LEFT_TAG_Y, 0.0, new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - MID_CUBE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y,\n MID_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - HIGH_CUBE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y,\n HIGH_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_THREE = new Pose3d[] {\n new Pose3d(\n LEFT_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n LEFT_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n LEFT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_FOUR = new Pose3d[] {\n new Pose3d(\n MIDDLE_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_FIVE = new Pose3d[] {\n new Pose3d(MIDDLE_TAG_X + LOW_CUBE_X_CENTER_FROM_APRILTAG, MIDDLE_TAG_Y, 0.0, new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - MID_CUBE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y,\n MID_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - HIGH_CUBE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y,\n HIGH_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_SIX = new Pose3d[] {\n new Pose3d(\n MIDDLE_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n MIDDLE_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n MIDDLE_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_SEVEN = new Pose3d[] {\n new Pose3d(\n RIGHT_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y + Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_EIGHT = new Pose3d[] {\n new Pose3d(RIGHT_TAG_X + LOW_CUBE_X_CENTER_FROM_APRILTAG, RIGHT_TAG_Y, 0.0, new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - MID_CUBE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y,\n MID_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - HIGH_CUBE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y,\n HIGH_CUBE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n COLUMN_NINE = new Pose3d[] {\n new Pose3d(\n RIGHT_TAG_X + LOW_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n 0.0,\n new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - MID_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n MID_CONE_NODE_HEIGHT_METERS,\n new Rotation3d()),\n new Pose3d(\n RIGHT_TAG_X - HIGH_CONE_X_CENTER_FROM_APRILTAG,\n RIGHT_TAG_Y - Y_BETWEEN_COLUMNS_METERS,\n HIGH_CONE_NODE_HEIGHT_METERS,\n new Rotation3d())\n };\n\n WaypointConstants.update();\n }\n }\n}" } ]
import edu.wpi.first.math.filter.LinearFilter; import edu.wpi.first.wpilibj.PowerDistribution; import edu.wpi.first.wpilibj2.command.CommandScheduler; import org.frcteam2910.c2023.config.RobotIdentity; import org.frcteam2910.c2023.subsystems.led.LEDSubsystem; import org.frcteam2910.c2023.util.DriverReadouts; import org.frcteam2910.c2023.util.GamePiece; import org.frcteam2910.c2023.util.MacAddressUtil; import org.frcteam2910.c2023.util.constants.FieldConstants; import org.littletonrobotics.junction.LogFileUtil; import org.littletonrobotics.junction.LoggedRobot; import org.littletonrobotics.junction.Logger; import org.littletonrobotics.junction.networktables.NT4Publisher; import org.littletonrobotics.junction.wpilog.WPILOGReader; import org.littletonrobotics.junction.wpilog.WPILOGWriter;
6,999
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.frcteam2910.c2023; public class Robot extends LoggedRobot { private RobotContainer robotContainer; private final PowerDistribution powerDistribution = new PowerDistribution(); private final LinearFilter average = LinearFilter.movingAverage(50); @Override public void robotInit() { Logger logger = Logger.getInstance(); // Record metadata logger.recordMetadata("GitRevision", String.valueOf(BuildInfo.GIT_REVISION)); logger.recordMetadata("GitSHA", BuildInfo.GIT_SHA); logger.recordMetadata("GitDate", BuildInfo.GIT_DATE); logger.recordMetadata("GitBranch", BuildInfo.GIT_BRANCH); logger.recordMetadata("BuildDate", BuildInfo.BUILD_DATE); logger.recordMetadata("BuildUnixTime", String.valueOf(BuildInfo.BUILD_UNIX_TIME)); switch (BuildInfo.DIRTY) { case 0: logger.recordMetadata("GitDirty", "Clean"); break; case 1: logger.recordMetadata("GitDirty", "Dirty"); break; default: logger.recordMetadata("GitDirty", "Error"); break; } logger.recordMetadata("Robot Name", RobotIdentity.getIdentity().toString());
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.frcteam2910.c2023; public class Robot extends LoggedRobot { private RobotContainer robotContainer; private final PowerDistribution powerDistribution = new PowerDistribution(); private final LinearFilter average = LinearFilter.movingAverage(50); @Override public void robotInit() { Logger logger = Logger.getInstance(); // Record metadata logger.recordMetadata("GitRevision", String.valueOf(BuildInfo.GIT_REVISION)); logger.recordMetadata("GitSHA", BuildInfo.GIT_SHA); logger.recordMetadata("GitDate", BuildInfo.GIT_DATE); logger.recordMetadata("GitBranch", BuildInfo.GIT_BRANCH); logger.recordMetadata("BuildDate", BuildInfo.BUILD_DATE); logger.recordMetadata("BuildUnixTime", String.valueOf(BuildInfo.BUILD_UNIX_TIME)); switch (BuildInfo.DIRTY) { case 0: logger.recordMetadata("GitDirty", "Clean"); break; case 1: logger.recordMetadata("GitDirty", "Dirty"); break; default: logger.recordMetadata("GitDirty", "Error"); break; } logger.recordMetadata("Robot Name", RobotIdentity.getIdentity().toString());
logger.recordMetadata("Robot MAC Address", MacAddressUtil.getMACAddress());
4
2023-11-03 02:12:12+00:00
8k
YunaBraska/type-map
src/main/java/berlin/yuna/typemap/model/ConcurrentTypeMap.java
[ { "identifier": "ArgsDecoder", "path": "src/main/java/berlin/yuna/typemap/logic/ArgsDecoder.java", "snippet": "public class ArgsDecoder {\n\n public static Map<String, TypeSet> argsOf(final String input) {\n final Map<String, TypeSet> result = new HashMap<>();\n final List<Integer[]> keyRanges = getKeyRanges(input);\n\n for (int i = 0; i < keyRanges.size(); i++) {\n final Integer[] range = keyRanges.get(i);\n final int offsetEnd = i + 1 < keyRanges.size() ? keyRanges.get(i + 1)[0] : input.length();\n final String key = input.substring(range[0], range[1]);\n final String cleanKey = key.substring(key.startsWith(\"--\") ? 2 : 1).trim();\n final String value = input.substring(range[1] + 1, offsetEnd);\n final TypeSet values = result.computeIfAbsent(cleanKey, v -> new TypeSet());\n values.addAll((hasText(value) ? handleValue(value.trim()) : singletonList(true)));\n result.put(cleanKey, values);\n }\n return result;\n }\n\n public static boolean hasText(final String str) {\n return (str != null && !str.isEmpty() && containsText(str));\n }\n\n protected static TypeList handleValue(final String value) {\n if ((value.startsWith(\"'\") && value.endsWith(\"'\")) || (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\"))) {\n return new TypeList().addd(convertToType(value.substring(1, value.length() - 1)));\n }\n return new TypeList().adddAll(Arrays.stream(value.split(\"\\\\s+\", -1)).map(ArgsDecoder::convertToType).collect(Collectors.toList()));\n }\n\n private static Object convertToType(final String string) {\n return string.equalsIgnoreCase(\"true\") || string.equalsIgnoreCase(\"false\") ? string.equalsIgnoreCase(\"true\") : string;\n }\n\n private static List<Integer[]> getKeyRanges(final String input) {\n final List<Integer[]> keyRanges = new ArrayList<>();\n int keyIndex = -1;\n boolean inQuotes = false;\n\n for (int i = 0; i < input.length(); i++) {\n final char c = input.charAt(i);\n if (c == '\"' || c == '\\'') {\n inQuotes = !inQuotes;\n } else if (!inQuotes && keyIndex == -1 && c == '-') {\n keyIndex = i;\n } else if (!inQuotes && keyIndex != -1 && ((c == '=') || c == ' ')) {\n keyRanges.add(new Integer[]{keyIndex, i});\n keyIndex = -1;\n }\n }\n return keyRanges;\n }\n\n private static boolean containsText(final CharSequence str) {\n final int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n private ArgsDecoder() {\n // static util class\n }\n}" }, { "identifier": "JsonDecoder", "path": "src/main/java/berlin/yuna/typemap/logic/JsonDecoder.java", "snippet": "public class JsonDecoder {\n\n /**\n * Converts a JSON string to a LinkedTypeMap.\n * This method first converts the JSON string into an appropriate Java object (Map, List, or other types)\n * using the objectOf method. If the result is a LinkedTypeMap, it returns the map directly.\n * Otherwise, it creates a new LinkedTypeMap with a single entry where the key is an empty string\n * and the value is the result object. If the JSON string represents an array or a non-map object,\n * it's encapsulated within this single-entry map.\n *\n * @param json The JSON string to convert.\n * @return A LinkedTypeMap representing the JSON object, or an empty LinkedTypeMap if the JSON string is null or invalid.\n */\n public static LinkedTypeMap jsonMapOf(final String json) {\n final Object result = jsonOf(json);\n if (result instanceof LinkedTypeMap) {\n return (LinkedTypeMap) result;\n } else if (result != null) {\n return new LinkedTypeMap().putt(\"\", result);\n }\n return new LinkedTypeMap();\n }\n\n /**\n * Converts a JSON string to a List of objects.\n * This method first converts the JSON string into an appropriate Java object (Map, List, or other types)\n * using the objectOf method. If the result is a List, it is cast and returned directly.\n * If the result is a LinkedTypeMap, it creates a new List containing this map as a single element.\n * This method is useful for ensuring that JSON arrays are converted to Lists, but it can also encapsulate\n * non-array JSON objects within a List.\n *\n * @param json The JSON string to convert.\n * @return A List of objects representing the JSON array or containing the JSON object, or an empty List if the JSON string is null or invalid.\n */\n public static TypeList jsonListOf(final String json) {\n final Object result = jsonOf(json);\n if (result instanceof TypeList) {\n return (TypeList) result;\n } else if (result instanceof LinkedTypeMap) {\n final TypeList list = new TypeList();\n list.add(result);\n return list;\n } else if (result != null) {\n return new TypeList(singletonList(result));\n }\n return new TypeList();\n }\n\n /**\n * Converts a JSON string to a Map, List, or Object.\n * Handles basic structures of JSON including nested objects and arrays.\n * Note: This implementation is simplified and may not handle all edge cases or complex JSON structures.\n *\n * @param json The JSON string to convert.\n * @return A Map, List, or Object representing the JSON structure.\n */\n public static Object jsonOf(final String json) {\n final String input = json == null ? null : json.trim();\n if (json == null || json.equals(\"{}\")) {\n return null;\n } else if (input.startsWith(\"{\") && input.endsWith(\"}\")) {\n final LinkedTypeMap map = toMap(removeWrapper(input).trim());\n return map.size() == 1 && map.containsKey(\"\") ? map.get(\"\") : map;\n } else if (input.startsWith(\"[\") && input.endsWith(\"]\")) {\n return toList(removeWrapper(input).trim());\n } else if (input.startsWith(\"\\\"\") && input.endsWith(\"\\\"\")) {\n return unescapeJson(input.substring(1, input.length() - 1));\n } else {\n return convertToPrimitive(input);\n }\n }\n\n private static Object convertToPrimitive(final String value) {\n if (\"null\".equals(value)) {\n return null;\n } else if (\"true\".equals(value) || \"false\".equals(value)) {\n return Boolean.parseBoolean(value);\n } else {\n final Object result;\n if (value.contains(\".\") || value.contains(\"e\") || value.contains(\"E\")) {\n result = convertObj(value, Double.class);\n } else {\n result = convertObj(value, Long.class);\n }\n return result == null ? unescapeJson(value) : result;\n }\n }\n\n private static String removeWrapper(final String input) {\n return input.substring(1, input.length() - 1);\n }\n\n private static LinkedTypeMap toMap(final String json) {\n final LinkedTypeMap map = new LinkedTypeMap();\n for (final String pair : splitJson(json)) {\n final String[] keyValue = splitFirstBy(pair, ':');\n if (keyValue.length < 2) {\n map.put(\"\", jsonOf(pair));\n } else {\n final String key = unquote(keyValue[0].trim());\n final Object value = jsonOf(keyValue[1].trim());\n map.put(key, value);\n }\n }\n return map;\n }\n\n @SuppressWarnings(\"java:S3776\")\n private static String[] splitJson(final String json) {\n final TypeList parts = new TypeList();\n int braceCount = 0;\n int bracketCount = 0;\n boolean inString = false;\n final StringBuilder currentPart = new StringBuilder();\n\n for (int i = 0; i < json.length(); i++) {\n final char c = json.charAt(i);\n\n // Toggle the inString flag if we encounter a non-escaped quote\n if (c == '\"' && (i == 0 || json.charAt(i - 1) != '\\\\')) {\n inString = !inString;\n }\n\n if (!inString) {\n if (c == '{') braceCount++;\n if (c == '}') braceCount--;\n if (c == '[') bracketCount++;\n if (c == ']') bracketCount--;\n\n if (c == ',' && braceCount == 0 && bracketCount == 0) {\n parts.add(currentPart.toString());\n currentPart.setLength(0);\n continue;\n }\n }\n\n currentPart.append(c);\n }\n\n if (currentPart.length() > 0) {\n parts.add(currentPart.toString());\n }\n\n return parts.toArray(new String[0]);\n }\n\n @SuppressWarnings(\"SameParameterValue\")\n private static String[] splitFirstBy(final String string, final char c) {\n final int colonIndex = firstNonEscapedCar(string, c);\n return colonIndex == -1 ? new String[0] : new String[]{\n string.substring(0, colonIndex).trim(),\n string.substring(colonIndex + 1).trim()\n };\n }\n\n private static int firstNonEscapedCar(final String str, final char c) {\n boolean inString = false;\n for (int i = 0; i < str.length(); i++) {\n if (str.charAt(i) == '\"' && (i == 0 || str.charAt(i - 1) != '\\\\')) inString = !inString;\n if (str.charAt(i) == c && !inString) return i;\n }\n return -1;\n }\n\n private static String unquote(final String str) {\n return str.startsWith(\"\\\"\") && str.endsWith(\"\\\"\") ? removeWrapper(str) : str;\n }\n\n private static TypeList toList(final String json) {\n final TypeList list = new TypeList();\n for (final String element : splitJson(json)) {\n list.add(jsonOf(element.trim())); // Recursively parse each element\n }\n return list;\n }\n\n private JsonDecoder() {\n // static util class\n }\n}" }, { "identifier": "JsonEncoder", "path": "src/main/java/berlin/yuna/typemap/logic/JsonEncoder.java", "snippet": "public class JsonEncoder {\n\n @SuppressWarnings({\"java:S2386\"})\n public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();\n @SuppressWarnings({\"java:S2386\"})\n public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();\n\n static {\n JSON_ESCAPE_SEQUENCES.put('\"', \"\\\\\\\"\");\n JSON_ESCAPE_SEQUENCES.put('\\\\', \"\\\\\\\\\");\n JSON_ESCAPE_SEQUENCES.put('\\b', \"\\\\b\");\n JSON_ESCAPE_SEQUENCES.put('\\f', \"\\\\f\");\n JSON_ESCAPE_SEQUENCES.put('\\n', \"\\\\n\");\n JSON_ESCAPE_SEQUENCES.put('\\r', \"\\\\r\");\n JSON_ESCAPE_SEQUENCES.put('\\t', \"\\\\t\");\n JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));\n }\n\n /**\n * Converts any object to its JSON representation.\n * This method dispatches the conversion task based on the type of the object.\n * It handles Maps, Collections, Arrays (both primitive and object types),\n * and other objects. If the object is null, it returns an empty JSON object ({}).\n * Standalone objects are converted to JSON strings and wrapped in curly braces,\n * making them single-property JSON objects.\n *\n * @param object The object to be converted to JSON.\n * @return A JSON representation of the object as a String.\n * If the object is null, returns \"{}\".\n */\n public static String toJson(final Object object) {\n if (object == null) {\n return \"{}\";\n } else if (object instanceof Map) {\n return jsonOf((Map<?, ?>) object);\n } else if (object instanceof Collection) {\n return jsonOf((Collection<?>) object);\n } else if (object.getClass().isArray()) {\n return jsonOfArray(object, Object[]::new, Object.class);\n } else {\n return \"{\" + jsonify(object) + \"}\";\n }\n }\n\n /**\n * Escapes a String for JSON.\n * This method replaces special characters in a String with their corresponding JSON escape sequences.\n *\n * @param str The string to be escaped for JSON.\n * @return The escaped JSON string.\n */\n public static String escapeJsonValue(final String str) {\n return str == null ? null : str.chars()\n .mapToObj(c -> escapeJson((char) c))\n .collect(Collectors.joining());\n }\n\n\n /**\n * Escapes a character for JSON.\n * This method returns the JSON escape sequence for a given character, if necessary.\n *\n * @param c The character to be escaped for JSON.\n * @return The escaped JSON character as a String.\n */\n public static String escapeJson(final char c) {\n return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format(\"\\\\u%04x\", (int) c) : String.valueOf(c));\n }\n\n /**\n * Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.\n * <p>\n * This method iterates through a predefined set of JSON escape sequences (like \\\" for double quotes,\n * \\\\ for backslash, \\n for newline, etc.) and replaces them in the input string with the actual characters\n * they represent. The method is designed to process a JSON-encoded string and return a version with\n * standard characters, making it suitable for further processing or display.\n * <p>\n * Note: This method assumes that the input string is a valid JSON string with correct escape sequences.\n * It does not perform JSON validation.\n *\n * @param str The JSON string with escape sequences to be unescaped.\n * @return The unescaped version of the JSON string.\n */\n public static String unescapeJson(final String str) {\n String result = str;\n for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {\n result = result.replace(entry.getKey(), entry.getValue());\n }\n return result;\n }\n\n private static String jsonOf(final Map<?, ?> map) {\n return map.entrySet().stream()\n .map(entry -> jsonify(entry.getKey()) + \":\" + jsonify(entry.getValue()))\n .collect(Collectors.joining(\",\", \"{\", \"}\"));\n }\n\n private static String jsonOf(final Collection<?> collection) {\n return collection.stream()\n .map(JsonEncoder::jsonify)\n .collect(Collectors.joining(\",\", \"[\", \"]\"));\n }\n\n @SuppressWarnings(\"SameParameterValue\")\n private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) {\n return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType))\n .map(JsonEncoder::jsonify)\n .collect(Collectors.joining(\",\", \"[\", \"]\")) : \"null\";\n }\n\n private static String jsonify(final Object obj) {\n if (obj == null) {\n return \"null\";\n } else if (obj instanceof String) {\n return \"\\\"\" + escapeJsonValue((String) obj) + \"\\\"\";\n } else if (obj instanceof Number || obj instanceof Boolean) {\n return obj.toString();\n } else if (obj instanceof Map) {\n return jsonOf((Map<?, ?>) obj);\n } else if (obj instanceof Collection) {\n return jsonOf((Collection<?>) obj);\n } else if (obj.getClass().isArray()) {\n return jsonOfArray(obj, Object[]::new, Object.class);\n } else {\n final String str = convertObj(obj, String.class);\n return str == null ? \"null\" : \"\\\"\" + escapeJsonValue(str) + \"\\\"\";\n }\n }\n\n private JsonEncoder() {\n // static util class\n }\n}" }, { "identifier": "collectionOf", "path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java", "snippet": "public static TypeList collectionOf(final Object input) {\n return collectionOf(input, TypeList::new, Object.class);\n}" }, { "identifier": "convertObj", "path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java", "snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic static <T> T convertObj(final Object value, final Class<T> targetType) {\n if (value == null) return null;\n if (targetType.isInstance(value)) {\n return targetType.cast(value);\n }\n\n // Handle non-empty arrays, collections, map\n final Object firstValue = getFirstItem(value);\n if (firstValue != null) {\n return convertObj(firstValue, targetType);\n }\n\n // Enums\n if (targetType.isEnum()) {\n return (T) enumOf(String.valueOf(value), (Class<Enum>) targetType);\n }\n\n final Class<?> sourceType = value.getClass();\n final Map<Class<?>, FunctionOrNull> conversions = TYPE_CONVERSIONS.getOrDefault(targetType, Collections.emptyMap());\n\n // First try to find exact match\n final FunctionOrNull exactMatch = conversions.get(sourceType);\n if (exactMatch != null) {\n return targetType.cast(exactMatch.apply(value));\n }\n\n // Fallback to more general converters\n for (final Map.Entry<Class<?>, FunctionOrNull> entry : conversions.entrySet()) {\n if (entry.getKey().isAssignableFrom(sourceType)) {\n return targetType.cast(entry.getValue().apply(value));\n }\n }\n\n // Fallback to string convert\n if (!String.class.equals(sourceType)) {\n return convertObj(String.valueOf(value), targetType);\n }\n return null;\n}" }, { "identifier": "convertAndMap", "path": "src/main/java/berlin/yuna/typemap/model/TypeMap.java", "snippet": "protected static <K, V, M extends Map<K, V>> M convertAndMap(final Object value, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) {\n if (output != null && keyType != null && valueType != null && value instanceof Map<?, ?>) {\n final Map<?, ?> input = (Map<?, ?>) value;\n return mapOf(input, output, keyType, valueType);\n }\n return ofNullable(output).map(Supplier::get).orElse(null);\n}" }, { "identifier": "treeGet", "path": "src/main/java/berlin/yuna/typemap/model/TypeMap.java", "snippet": "protected static Object treeGet(final Object mapOrCollection, final Object... path) {\n if (path == null || path.length == 0) {\n return null;\n }\n\n Object value = mapOrCollection;\n for (final Object key : path) {\n if (key == null || value == null) {\n return null;\n } else if (value instanceof Map<?, ?>) {\n value = ((Map<?, ?>) value).get(key);\n } else if (value instanceof Collection<?> && key instanceof Number) {\n final int index = ((Number) key).intValue();\n final List<?> list = (List<?>) value;\n value = (index >= 0 && index < list.size()) ? list.get(index) : null;\n } else if (value.getClass().isArray() && key instanceof Number) {\n final int index = ((Number) key).intValue();\n final AtomicInteger itemCount = new AtomicInteger(0);\n final AtomicReference<Object> result = new AtomicReference<>(null);\n iterateOverArray(value, item -> {\n if (result.get() == null && index == itemCount.getAndIncrement())\n result.set(item);\n });\n return result.get();\n } else {\n value = null;\n }\n }\n return value;\n}" } ]
import berlin.yuna.typemap.logic.ArgsDecoder; import berlin.yuna.typemap.logic.JsonDecoder; import berlin.yuna.typemap.logic.JsonEncoder; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.IntFunction; import java.util.function.Supplier; import static berlin.yuna.typemap.logic.TypeConverter.collectionOf; import static berlin.yuna.typemap.logic.TypeConverter.convertObj; import static berlin.yuna.typemap.model.TypeMap.convertAndMap; import static berlin.yuna.typemap.model.TypeMap.treeGet; import static java.util.Optional.ofNullable;
5,117
package berlin.yuna.typemap.model; /** * {@link ConcurrentTypeMap} is a specialized implementation of {@link ConcurrentHashMap} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link ConcurrentTypeMap} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class ConcurrentTypeMap extends ConcurrentHashMap<Object, Object> implements TypeMapI<ConcurrentTypeMap> { /** * Default constructor for creating an empty TypeMap. */ public ConcurrentTypeMap() { this((Map<?, ?>) null); } /** * Constructs a new {@link ConcurrentTypeMap} of the specified json. */ public ConcurrentTypeMap(final String json) { this(JsonDecoder.jsonMapOf(json)); } /** * Constructs a new {@link ConcurrentTypeMap} of the specified command line arguments. */ public ConcurrentTypeMap(final String[] cliArgs) {
package berlin.yuna.typemap.model; /** * {@link ConcurrentTypeMap} is a specialized implementation of {@link ConcurrentHashMap} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link ConcurrentTypeMap} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class ConcurrentTypeMap extends ConcurrentHashMap<Object, Object> implements TypeMapI<ConcurrentTypeMap> { /** * Default constructor for creating an empty TypeMap. */ public ConcurrentTypeMap() { this((Map<?, ?>) null); } /** * Constructs a new {@link ConcurrentTypeMap} of the specified json. */ public ConcurrentTypeMap(final String json) { this(JsonDecoder.jsonMapOf(json)); } /** * Constructs a new {@link ConcurrentTypeMap} of the specified command line arguments. */ public ConcurrentTypeMap(final String[] cliArgs) {
this(ArgsDecoder.argsOf(String.join(" ", cliArgs)));
0
2023-11-09 14:40:13+00:00
8k
estkme-group/InfiLPA
app/src/main/java/com/infineon/esim/lpa/lpa/task/ProfileActionTask.java
[ { "identifier": "ProfileActionType", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/enums/ProfileActionType.java", "snippet": "public enum ProfileActionType {\n PROFILE_ACTION_ENABLE,\n PROFILE_ACTION_DELETE,\n PROFILE_ACTION_DISABLE,\n PROFILE_ACTION_SET_NICKNAME,\n}" }, { "identifier": "ProfileMetadata", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/profile/ProfileMetadata.java", "snippet": "final public class ProfileMetadata implements Parcelable {\n private static final String TAG = ProfileMetadata.class.getName();\n\n public static final String STATE_ENABLED = \"Enabled\";\n public static final String STATE_DISABLED = \"Disabled\";\n\n private static final String ICCID = \"ICCID\";\n private static final String STATE = \"STATE\";\n private static final String PROFILECLASS = \"CLASS\";\n private static final String NAME = \"NAME\";\n private static final String PROVIDER_NAME = \"PROVIDER_NAME\";\n private static final String NICKNAME = \"NICKNAME\";\n private static final String ICON = \"ICON\";\n\n private final Map<String, String> profileMetadataMap;\n\n static public String formatIccidUserString(String iccidRawString) {\n // swap the odd/even characters to form a new string\n // ignoring the second last char\n int i = 0;\n StringBuilder newText = new StringBuilder();\n\n while(i < iccidRawString.length() - 1) {\n newText.append(iccidRawString.charAt(i + 1));\n newText.append(iccidRawString.charAt(i));\n i += 2;\n }\n\n if (newText.charAt(newText.length() -1) == 'F') {\n newText.deleteCharAt(newText.length() -1);\n }\n\n return newText.toString();\n }\n\n static public String formatProfileClassString(String profileclass) {\n StringBuilder newText = new StringBuilder();\n if (profileclass != null) {\n switch (profileclass) {\n case \"0\":\n newText.append(\"Testing\");\n break;\n case \"1\":\n newText.append(\"Provisioning\");\n break;\n case \"2\":\n newText.append(\"Operational\");\n break;\n default:\n newText.append(\"Unknown\");\n break;\n }\n } else {\n newText.append(\"Null\");\n }\n\n return newText.toString();\n }\n\n public ProfileMetadata(Map<String, String> profileMetadataMap) {\n this.profileMetadataMap = new HashMap<>(profileMetadataMap);\n }\n\n public ProfileMetadata(@NonNull String iccid,\n @NonNull String profileState,\n @NonNull String profileName,\n @NonNull String serviceProviderName,\n @Nullable String profileclass,\n @Nullable String profileNickname,\n @Nullable String icon) {\n profileMetadataMap = new HashMap<>();\n initialize(iccid, profileState, profileName, serviceProviderName, profileclass, profileNickname, icon);\n }\n\n public ProfileMetadata(@NonNull Iccid iccid,\n @NonNull ProfileState profileState,\n @NonNull BerUTF8String profileName,\n @NonNull BerUTF8String serviceProviderName,\n @Nullable ProfileClass profileClass,\n @Nullable BerUTF8String profileNickname,\n @Nullable BerOctetString icon) {\n profileMetadataMap = new HashMap<>();\n\n String nicknameString = null;\n String iconString = null;\n String profileClassString = null;\n if(profileNickname != null) {\n nicknameString = profileNickname.toString();\n }\n if(icon != null) {\n iconString = icon.toString();\n }\n if(profileClass != null) {\n profileClassString = profileClass.toString();\n }\n initialize(iccid.toString(),\n ProfileStates.getString(profileState),\n profileName.toString(),\n serviceProviderName.toString(),\n profileClassString,\n nicknameString,\n iconString);\n }\n\n public ProfileMetadata(@NonNull ProfileInfo profileInfo) {\n this(profileInfo.getIccid(),\n profileInfo.getProfileState(),\n profileInfo.getProfileName(),\n profileInfo.getServiceProviderName(),\n profileInfo.getProfileClass(),\n profileInfo.getProfileNickname(),\n profileInfo.getIcon());\n }\n\n public ProfileMetadata(StoreMetadataRequest storeMetadataRequest) {\n this(storeMetadataRequest.getIccid(),\n new ProfileState(0),\n storeMetadataRequest.getProfileName(),\n storeMetadataRequest.getServiceProviderName(),\n storeMetadataRequest.getProfileClass(),\n null,\n null);\n }\n\n private void initialize(@NonNull String iccid,\n @NonNull String state,\n @NonNull String name,\n @NonNull String provider,\n @Nullable String profileclass,\n @Nullable String nickname,\n @Nullable String icon) {\n\n profileMetadataMap.put(NAME, name);\n profileMetadataMap.put(ICCID, iccid);\n profileMetadataMap.put(STATE, state);\n profileMetadataMap.put(PROVIDER_NAME, provider);\n\n if(nickname != null) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n if(icon != null) {\n profileMetadataMap.put(ICON, icon);\n }\n if(profileclass != null){\n profileMetadataMap.put(PROFILECLASS, profileclass);\n }\n }\n\n public Boolean hasNickname() {\n return (getNickname() != null) && (!getNickname().equals(\"\"));\n }\n\n public void setEnabled(boolean isEnabled) {\n if(isEnabled) {\n profileMetadataMap.replace(STATE, STATE_ENABLED);\n } else {\n profileMetadataMap.replace(STATE, STATE_DISABLED);\n }\n }\n\n public Boolean isEnabled() {\n return getState().equals(STATE_ENABLED);\n }\n\n public String getName() {\n return profileMetadataMap.get(NAME);\n }\n\n public String getIccid() {\n return profileMetadataMap.get(ICCID);\n }\n\n public String getState() {\n return profileMetadataMap.get(STATE);\n }\n\n public String getProfileclass() {\n return profileMetadataMap.get(PROFILECLASS);\n }\n\n public String getProvider() {\n return profileMetadataMap.get(PROVIDER_NAME);\n }\n\n public String getNickname() {\n return profileMetadataMap.get(NICKNAME);\n }\n\n private String getIconString() {\n return profileMetadataMap.get(ICON);\n }\n\n public void setNickname(String nickname) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeString(getName());\n out.writeString(getIccid());\n out.writeString(getState());\n out.writeString(getProfileclass());\n out.writeString(getProvider());\n out.writeString(getNickname());\n out.writeString(getIconString());\n }\n\n public static final Parcelable.Creator<ProfileMetadata> CREATOR = new Parcelable.Creator<ProfileMetadata>() {\n public ProfileMetadata createFromParcel(Parcel in) {\n return new ProfileMetadata(in);\n }\n\n public ProfileMetadata[] newArray(int size) {\n return new ProfileMetadata[size];\n }\n };\n\n private ProfileMetadata(Parcel in) {\n profileMetadataMap = new HashMap<>();\n profileMetadataMap.put(NAME, in.readString());\n profileMetadataMap.put(ICCID, in.readString());\n profileMetadataMap.put(STATE, in.readString());\n profileMetadataMap.put(PROFILECLASS, in.readString());\n profileMetadataMap.put(PROVIDER_NAME, in.readString());\n profileMetadataMap.put(NICKNAME, in.readString());\n profileMetadataMap.put(ICON, in.readString());\n }\n\n @NonNull\n @Override\n public String toString() {\n return \"Profile{\" +\n \"profileMetadataMap=\" + profileMetadataMap +\n '}';\n }\n\n public Icon getIcon() {\n String iconBytesHex = profileMetadataMap.get(ICON);\n\n if(iconBytesHex != null) {\n byte[] iconBytes = Bytes.decodeHexString(iconBytesHex);\n return Icon.createWithData(iconBytes, 0, iconBytes.length);\n } else {\n return null;\n }\n }\n}" }, { "identifier": "EnableResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/EnableResult.java", "snippet": "public class EnableResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_DISABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int WRONG_PROFILE_REENABLING = 4;\n public static final int CAT_BUSY = 5;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_DISABLED_STATE, \"Profile not in disabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(WRONG_PROFILE_REENABLING, \"Wrong profile reenabling.\");\n lookup.put(CAT_BUSY, \"CAT busy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public EnableResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}" }, { "identifier": "OperationResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/OperationResult.java", "snippet": "public interface OperationResult {\n\n boolean isOk();\n boolean equals(int value);\n String getDescription();\n}" }, { "identifier": "HandleNotificationsResult", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/HandleNotificationsResult.java", "snippet": "public class HandleNotificationsResult extends RemoteOperationResult {\n\n public HandleNotificationsResult() {\n super();\n }\n\n public HandleNotificationsResult(RemoteError remoteError) {\n super(remoteError);\n }\n}" }, { "identifier": "LocalProfileAssistant", "path": "app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java", "snippet": "public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer {\n private static final String TAG = LocalProfileAssistant.class.getName();\n\n private final StatusAndEventHandler statusAndEventHandler;\n private final MutableLiveData<ProfileList> profileList;\n private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver;\n\n private EuiccConnection euiccConnection;\n\n private EuiccInfo euiccInfo;\n private AuthenticateResult authenticateResult;\n private DownloadResult downloadResult;\n private CancelSessionResult cancelSessionResult;\n\n public LocalProfileAssistant(EuiccManager euiccManager, StatusAndEventHandler statusAndEventHandler) {\n super();\n Log.debug(TAG,\"Creating LocalProfileAssistant...\");\n\n this.networkStatusBroadcastReceiver = new NetworkStatusBroadcastReceiver(this);\n this.statusAndEventHandler = statusAndEventHandler;\n this.profileList = new MutableLiveData<>();\n\n networkStatusBroadcastReceiver.registerReceiver();\n euiccManager.setEuiccConnectionConsumer(this);\n }\n\n public MutableLiveData<ProfileList> getProfileListLiveData() {\n return profileList;\n }\n\n public EuiccInfo getEuiccInfo() {\n return euiccInfo;\n }\n\n public AuthenticateResult getAuthenticateResult() {\n return authenticateResult;\n }\n\n public DownloadResult getDownloadResult() {\n return downloadResult;\n }\n\n public CancelSessionResult getCancelSessionResult() {\n return cancelSessionResult;\n }\n\n public Boolean resetEuicc() throws Exception {\n if(euiccConnection == null) {\n throw new Exception(\"Error: eUICC connection not available to LPA.\");\n } else {\n return euiccConnection.resetEuicc();\n }\n }\n\n public void refreshProfileList() {\n Log.debug(TAG,\"Refreshing profile list.\");\n statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_STARTED);\n\n new TaskRunner().executeAsync(new GetProfileListTask(this),\n result -> {\n statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_FINISHED);\n profileList.setValue(result);\n },\n e -> statusAndEventHandler.onError(new Error(\"Exception during getting of profile list.\", e.getMessage())));\n }\n\n public void refreshEuiccInfo() {\n Log.debug(TAG, \"Refreshing eUICC info.\");\n statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED);\n\n new TaskRunner().executeAsync(new GetEuiccInfoTask(this),\n result -> {\n euiccInfo = result;\n statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Exception during getting of eUICC info.\", e.getMessage())));\n }\n\n public void enableProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED);\n\n if(profile.isEnabled()) {\n Log.debug(TAG, \"Profile already enabled!\");\n statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED);\n return;\n }\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_ENABLE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during enabling profile.\", e.getMessage())));\n }\n\n public void disableProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED);\n\n if(!profile.isEnabled()) {\n Log.debug(TAG, \"Profile already disabled!\");\n statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED);\n return;\n }\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_DISABLE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during disabling of profile.\", e.getMessage())));\n }\n\n public void deleteProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED);\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_DELETE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during deleting of profile.\", e.getMessage())));\n }\n\n\n public void setNickname(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED);\n\n ProfileActionTask profileActionTask = new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_SET_NICKNAME,\n profile);\n\n new TaskRunner().executeAsync(profileActionTask,\n result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during setting nickname of profile.\", e.getMessage())));\n }\n\n public void handleAndClearAllNotifications() {\n statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED);\n\n HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this);\n\n new TaskRunner().executeAsync(handleAndClearAllNotificationsTask,\n result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during clearing of all eUICC notifications.\", e.getMessage())));\n }\n\n public void startAuthentication(ActivationCode activationCode) {\n authenticateResult = null;\n statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED);\n\n AuthenticateTask authenticateTask = new AuthenticateTask(\n this,\n activationCode);\n\n new TaskRunner().executeAsync(authenticateTask,\n authenticateResult -> {\n postProcessAuthenticate(authenticateResult);\n statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error authentication of profile download.\", e.getMessage())));\n }\n\n public void postProcessAuthenticate(AuthenticateResult authenticateResult) {\n this.authenticateResult = authenticateResult;\n\n if(authenticateResult.getSuccess()) {\n // Check if there is a matching profile already installed\n ProfileMetadata newProfile = authenticateResult.getProfileMetadata();\n ProfileMetadata matchingProfile = null;\n if (newProfile != null) {\n ProfileList profileList = this.profileList.getValue();\n if(profileList != null) {\n matchingProfile = profileList.findMatchingProfile(newProfile.getIccid());\n }\n if ((matchingProfile != null) && (matchingProfile.getNickname() != null)) {\n Log.debug(TAG, \"Profile already installed: \" + matchingProfile.getNickname());\n String errorMessage = \"Profile with this ICCID already installed: \" + matchingProfile.getNickname();\n statusAndEventHandler.onError(new Error(\"Profile already installed!\", errorMessage));\n }\n }\n }\n }\n\n public void startProfileDownload(String confirmationCode) {\n downloadResult = null;\n statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_STARTED);\n\n new TaskRunner().executeAsync(\n new DownloadTask(this, confirmationCode),\n downloadResult -> {\n postProcessDownloadProfile(downloadResult);\n statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error during download of profile.\", e.getMessage())));\n }\n\n\n private void postProcessDownloadProfile(DownloadResult downloadResult) {\n this.downloadResult = downloadResult;\n ProfileList profileList = this.profileList.getValue();\n\n Log.debug(TAG, \"Post processing new profile. download success: \" + downloadResult.getSuccess());\n if(downloadResult.getSuccess() && (profileList != null)) {\n ProfileMetadata profileMetadata = authenticateResult.getProfileMetadata();\n Log.debug(TAG, \"Post processing new profile: \" + profileMetadata);\n\n Log.debug(TAG, \"Profile nickname: \\\"\" + profileMetadata.getNickname() + \"\\\"\");\n if(!profileMetadata.hasNickname()) {\n String nickname = profileList.getUniqueNickname(profileMetadata);\n\n Log.debug(TAG, \"Profile does not have a nickname. So set a new one: \\\"\" + nickname + \"\\\"\");\n profileMetadata.setNickname(nickname);\n setNickname(profileMetadata);\n }\n }\n }\n\n public void startCancelSession(long cancelSessionReason) {\n Log.debug(TAG, \"Cancel session: \" + cancelSessionReason);\n\n statusAndEventHandler.onStatusChange(ActionStatus.CANCEL_SESSION_STARTED);\n\n CancelSessionTask cancelSessionTask = new CancelSessionTask(\n this,\n cancelSessionReason);\n\n new TaskRunner().executeAsync(cancelSessionTask,\n result -> {\n cancelSessionResult = result;\n statusAndEventHandler.onStatusChange(ActionStatus.CANCEL_SESSION_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error cancelling session.\", e.getMessage())));\n }\n\n @Override\n public void onEuiccConnectionUpdate(EuiccConnection euiccConnection) {\n Log.debug(TAG, \"Updated eUICC connection.\");\n this.euiccConnection = euiccConnection;\n super.setEuiccChannel(euiccConnection);\n\n if(euiccConnection != null) {\n refreshProfileList();\n }\n }\n\n @Override\n public void onConnected() {\n Log.debug(TAG, \"Internet connection established.\");\n super.enableEs9PlusInterface();\n }\n\n @Override\n public void onDisconnected() {\n Log.debug(TAG, \"Internet connection lost.\");\n super.disableEs9PlusInterface();\n }\n\n @Override\n protected void finalize() throws Throwable {\n super.finalize();\n networkStatusBroadcastReceiver.unregisterReceiver();\n }\n}" }, { "identifier": "Log", "path": "app/src/test/java/com/infineon/esim/util/Log.java", "snippet": "final public class Log {\n\n // Ref:\n // https://stackoverflow.com/questions/8355632/how-do-you-usually-tag-log-entries-android\n public static String getFileLineNumber() {\n String info = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getFileLineNumber\")) {\n info = \"(\"+ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber()+\")\";\n }\n }\n return info;\n }\n\n public static void verbose(final String tag, final String msg) {\n System.out.println(\"V - \" + tag + \": \" + msg);\n }\n\n public static void debug(final String tag, final String msg) {\n System.out.println(\"D - \" + tag + \": \" + msg);\n }\n\n public static void info(final String tag, final String msg) {\n System.out.println(\"I- \" + tag + \": \" + msg);\n }\n\n public static void error(final String msg) {\n System.out.println(\"E- \" + msg);\n }\n\n public static void error(final String tag, final String msg) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n }\n\n public static void error(final String tag, final String msg, final Throwable error) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n error.printStackTrace();\n }\n}" } ]
import java.util.concurrent.Callable; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.local.EnableResult; import com.infineon.esim.lpa.core.dtos.result.local.OperationResult; import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult; import com.infineon.esim.lpa.lpa.LocalProfileAssistant; import com.infineon.esim.util.Log;
5,956
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa.task; public class ProfileActionTask implements Callable<Void> { private static final String TAG = ProfileActionTask.class.getName(); private final LocalProfileAssistant lpa; private final ProfileActionType profileActionType; private final ProfileMetadata profile; private OperationResult profileOperationResult = null; public ProfileActionTask(LocalProfileAssistant lpa, ProfileActionType profileActionType, ProfileMetadata profile) { this.lpa = lpa; this.profileActionType = profileActionType; this.profile = profile; } @Override public Void call() throws Exception { switch (profileActionType) { case PROFILE_ACTION_ENABLE: profileOperationResult = lpa.enableProfile(profile.getIccid(), true); break; case PROFILE_ACTION_DISABLE: profileOperationResult = lpa.disableProfile(profile.getIccid()); break; case PROFILE_ACTION_DELETE: // If profile is currently enabled, disable it first if (profile.isEnabled()) { Log.info(TAG,"Profile that shall be deleted is enabled. First disable it."); profileOperationResult = lpa.disableProfile(profile.getIccid()); handleProfileOperationResult(profileOperationResult); performEuiccReset(); } Log.info(TAG,"Deleting the profile."); profileOperationResult = lpa.deleteProfile(profile.getIccid()); break; case PROFILE_ACTION_SET_NICKNAME: profileOperationResult = lpa.setNickname(profile.getIccid(), profile.getNickname()); break; } // Handle profile operation result handleProfileOperationResult(profileOperationResult); performEuiccReset(); // Send notification try {
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.lpa.task; public class ProfileActionTask implements Callable<Void> { private static final String TAG = ProfileActionTask.class.getName(); private final LocalProfileAssistant lpa; private final ProfileActionType profileActionType; private final ProfileMetadata profile; private OperationResult profileOperationResult = null; public ProfileActionTask(LocalProfileAssistant lpa, ProfileActionType profileActionType, ProfileMetadata profile) { this.lpa = lpa; this.profileActionType = profileActionType; this.profile = profile; } @Override public Void call() throws Exception { switch (profileActionType) { case PROFILE_ACTION_ENABLE: profileOperationResult = lpa.enableProfile(profile.getIccid(), true); break; case PROFILE_ACTION_DISABLE: profileOperationResult = lpa.disableProfile(profile.getIccid()); break; case PROFILE_ACTION_DELETE: // If profile is currently enabled, disable it first if (profile.isEnabled()) { Log.info(TAG,"Profile that shall be deleted is enabled. First disable it."); profileOperationResult = lpa.disableProfile(profile.getIccid()); handleProfileOperationResult(profileOperationResult); performEuiccReset(); } Log.info(TAG,"Deleting the profile."); profileOperationResult = lpa.deleteProfile(profile.getIccid()); break; case PROFILE_ACTION_SET_NICKNAME: profileOperationResult = lpa.setNickname(profile.getIccid(), profile.getNickname()); break; } // Handle profile operation result handleProfileOperationResult(profileOperationResult); performEuiccReset(); // Send notification try {
HandleNotificationsResult handleNotificationsResult = lpa.handleNotifications();
4
2023-11-06 02:41:13+00:00
8k