hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
65f80f2006d2cc9c95330695be0cc47b23c545db
3,725
package gov.uk.courtdata.laastatus.service; import gov.uk.courtdata.entity.WqCoreEntity; import gov.uk.courtdata.enums.JobStatus; import gov.uk.courtdata.enums.WQStatus; import gov.uk.courtdata.exception.MAATCourtDataException; import gov.uk.courtdata.model.CpJobStatus; import gov.uk.courtdata.repository.WqCoreRepository; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.*; import org.mockito.junit.MockitoJUnitRunner; import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CpJobStatusServiceTest { @InjectMocks private LaaStatusJobService laaStatusJobService; @Spy private WqCoreRepository wqCoreRepository; @Captor private ArgumentCaptor<WqCoreEntity> wqCoreCaptor; @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test public void givenStatusJobIsReceivedWithSUCCESSStatus_whenExecuteIsInvoked_thenStatusIsUpdated() { // given CpJobStatus cpJobStatus = CpJobStatus.builder() .laaStatusTransactionId(123456) .laaTransactionId(UUID.fromString("6f5b34ea-e038-4f1c-bfe5-d6bf622444f0")) .jobStatus(JobStatus.SUCCESS) .maatId(1234) .build(); WqCoreEntity wqCoreEntity = WqCoreEntity.builder().txId(123456).build(); //when when(wqCoreRepository.findById(Mockito.anyInt())) .thenReturn(Optional.of(wqCoreEntity)); laaStatusJobService.execute(cpJobStatus); //then verify(wqCoreRepository).save(wqCoreCaptor.capture()); assertThat(wqCoreCaptor.getValue().getTxId()).isEqualTo(123456); assertThat(wqCoreCaptor.getValue().getWqStatus()).isEqualTo(WQStatus.SUCCESS.value()); } @Test public void givenStatusJobIsReceivedWithFAILStatus_whenExecuteIsInvoked_thenStatusIsUpdated() { // given CpJobStatus cpJobStatus = CpJobStatus.builder() .laaStatusTransactionId(123456) .laaTransactionId(UUID.fromString("6f5b34ea-e038-4f1c-bfe5-d6bf622444f0")) .jobStatus(JobStatus.FAIL) .maatId(1234) .build(); WqCoreEntity wqCoreEntity = WqCoreEntity.builder().txId(123456).build(); //when when(wqCoreRepository.findById(Mockito.anyInt())) .thenReturn(Optional.of(wqCoreEntity)); laaStatusJobService.execute(cpJobStatus); //then verify(wqCoreRepository).save(wqCoreCaptor.capture()); assertThat(wqCoreCaptor.getValue().getTxId()).isEqualTo(123456); assertThat(wqCoreCaptor.getValue().getWqStatus()).isEqualTo(WQStatus.FAIL.value()); } @Test public void givenStatusJobIsReceivedWithSUCCESSStatusANDNoLAARecord_whenExecuteIsInvoked_thenExceptionISThrown() { // given CpJobStatus cpJobStatus = CpJobStatus.builder() .laaStatusTransactionId(123456) .laaTransactionId(UUID.fromString("6f5b34ea-e038-4f1c-bfe5-d6bf622444f0")) .jobStatus(JobStatus.FAIL) .maatId(1234) .build(); //when when(wqCoreRepository.findById(Mockito.anyInt())) .thenReturn(Optional.empty()); exceptionRule.expect(MAATCourtDataException.class); exceptionRule.expectMessage("No Record found for Maat ID- 1234, Txn ID-123456"); laaStatusJobService.execute(cpJobStatus); } }
33.558559
118
0.695034
882a47e64a8719d9e79b0720336da48b2c934a05
110
package com.richard.statemachine; public enum Event { SUBMIT, PAYMENT_RECEIVED, PAYMENT_FAILED }
13.75
33
0.727273
031d29270e739cb661a3a855aae94a5e86f90704
2,362
import org.checkerframework.checker.interning.qual.*; import java.util.*; public class StringIntern { // It would be very handy (and would eliminate quite a few annotations) // if any final variable that is initialized to something interned // (essentially, to a literal) were treated as implicitly @Interned. final String finalStringInitializedToInterned = "foo"; // implicitly @Interned final String finalString2 = new String("foo"); static final String finalStringStatic1 = "foo"; // implicitly @Interned static final String finalStringStatic2 = new String("foo"); static class HasFields { static final String finalStringStatic3 = "foo"; // implicitly @Interned static final String finalStringStatic4 = new String("foo"); } static class Foo { private static Map<Foo, @Interned Foo> pool = new HashMap<Foo, @Interned Foo>(); @SuppressWarnings("interning") public @Interned Foo intern() { if (!pool.containsKey(this)) { pool.put(this, (@Interned Foo)this); } return pool.get(this); } } // Another example of the "final initialized to interned" rule final Foo finalFooInitializedToInterned = new Foo().intern(); public void test(@Interned String arg) { String notInternedStr = new String("foo"); @Interned String internedStr = notInternedStr.intern(); internedStr = finalStringInitializedToInterned; // OK //:: error: (assignment.type.incompatible) internedStr = finalString2; // error @Interned Foo internedFoo = finalFooInitializedToInterned; // OK if (arg == finalStringStatic1) { } // OK //:: error: (not.interned) if (arg == finalStringStatic2) { } // error if (arg == HasFields.finalStringStatic3) { } // OK //:: error: (not.interned) if (arg == HasFields.finalStringStatic4) { } // error } private @Interned String base; static final String BASE_HASHCODE = "hashcode"; public void foo() { if (base == BASE_HASHCODE) { } } public @Interned String emptyString(boolean b) { if (b) { return ""; } else { return (""); } } }
35.253731
82
0.602879
271c1263b01e9182581947944aa21b30429a2554
420
package de.exxcellent.challenge.readers; import java.util.List; /** * Reader for JSON files. */ public class ReaderJSON implements Reader { private String filePath; public ReaderJSON(String filePath) { this.filePath = filePath; } @Override public List<String[]> read() { //TODO: Implement solution for reading JSON files. Not part of the challenge. return null; } }
20
85
0.661905
9bc1cc26368521937b343c109b39d60d0462ac4d
2,049
package org.firstinspires.ftc.teamcode; /* Main class of Operation where we set up the max time for each operation and all the other operations come from this class */ public class Operation { protected RoverRobot robot; public long timeoutMS=9999; public long startMS=System.currentTimeMillis(); public long curMS=startMS, lastTime=startMS; public double deltaTime =0; public boolean done=false; public boolean timeout=false; public long numLoops=0; public boolean stopDriveOnDone=true; public boolean coastOnStop=false; public Operation(RoverRobot robot) { this.robot = robot; } public boolean run() { return run(10); } public boolean run(long timeBetweenLoopsMS) { while(loop()) { robot.telemetry.update(); robot.sleep(timeBetweenLoopsMS); if (robot.opMode!=null && robot.opMode.isStopRequested()){ done(); return false; } } return !timeout; // true if we ran to completion, else false means we timed out } public boolean loop() { if (done) return false; numLoops++; curMS=System.currentTimeMillis(); deltaTime= ((double) (curMS - lastTime)) / 1000.0; lastTime = curMS; if (curMS-startMS > timeoutMS) { timeout=true; done(); return false;} return true; // keep looping ... } public void done() { done=true; if (stopDriveOnDone) { // if(!coastOnStop) robot.drive.setHaltModeCoast(false); robot.drive.stop(); if(!coastOnStop){ robot.sleep(500); robot.drive.setHaltModeCoast(true); } } } public double getRuntime() { double runtime=((double) (curMS - startMS)) / 1000.0; return runtime; // seconds } public String getResult() { return String.format("Loops=%d TotalTime=%3.1f",numLoops, getRuntime()); } }
28.458333
100
0.586628
76651884924f879028f5965faca9da16c27ff9e6
2,316
/* * Copyright 2015-present Open Networking Laboratory * * 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.onosproject.incubator.net.tunnel; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; import org.junit.Test; import org.onlab.packet.IpAddress; import org.onosproject.core.GroupId; import org.onosproject.net.provider.ProviderId; /** * Test of a tunnel event. */ public class TunnelEventTest { /** * Checks that the Order class is immutable. */ @Test public void testImmutability() { assertThatClassIsImmutable(TunnelEvent.class); } /** * Checks the operation of equals(), hashCode() and toString() methods. */ @Test public void testConstructor() { TunnelEndPoint src = IpTunnelEndPoint.ipTunnelPoint(IpAddress .valueOf(23423)); TunnelEndPoint dst = IpTunnelEndPoint.ipTunnelPoint(IpAddress .valueOf(32421)); GroupId groupId = new GroupId(92034); TunnelName tunnelName = TunnelName.tunnelName("TunnelName"); TunnelId tunnelId = TunnelId.valueOf("41654654"); ProviderId producerName1 = new ProviderId("producer1", "13"); Tunnel p1 = new DefaultTunnel(producerName1, src, dst, Tunnel.Type.VXLAN, Tunnel.State.ACTIVE, groupId, tunnelId, tunnelName, null); TunnelEvent e1 = new TunnelEvent(TunnelEvent.Type.TUNNEL_ADDED, p1); assertThat(e1, is(notNullValue())); assertThat(e1.type(), is(TunnelEvent.Type.TUNNEL_ADDED)); assertThat(e1.subject(), is(p1)); } }
37.354839
81
0.689119
b454acb4e13136da245db29373e64f5dbcc2a22b
1,575
package ru.unatco.rss.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import ru.unatco.rss.R; import ru.unatco.rss.model.Item; public class FeedAdapter extends BaseAdapter { private final LayoutInflater mInflater; private final List<Item> mItems; public FeedAdapter(LayoutInflater inflater, List<Item> items) { mInflater = inflater; mItems = items; } @Override public int getCount() { return mItems.size(); } @Override public Item getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.feed_item, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Item item = getItem(position); holder.mTitle.setText(item.getmTitle()); return convertView; } public static class ViewHolder { @Bind(R.id.title) TextView mTitle; public ViewHolder(View view) { ButterKnife.bind(this, view); } } }
23.507463
79
0.645714
71d9a69072eef8eecab0ca20387d9d7ec21a6322
1,788
package dcraft.db.util; public class UtilitiesAdapter { /* TODO rethink protected DatabaseManager db = null; protected DatabaseInterface conn = null; protected DatabaseTask task = null; // TODO protected TenantManager dm = null; replace this with a very simple concept of TM, used in indexing only protected TablesAdapter tables = null; // don't call for general code... public UtilitiesAdapter(DatabaseManager db) { this.db = db; this.conn = db.allocateAdapter(); RecordStruct req = new RecordStruct(); req.withField("Replicate", false); // means this should replicate, where as Replicating means we are doing replication currently req.withField("Name", "dcRebuildIndexes"); req.withField("Stamp", this.db.allocateStamp(0)); req.withField("Tenant", DB_GLOBAL_ROOT_TENANT); this.task = new DatabaseTask(); this.task.setRequest(req); this.tables = new TablesAdapter(conn, task); } public void rebuildIndexes() { TablesAdapter ta = new TablesAdapter(conn, task); BigDateTime when = BigDateTime.nowDateTime(); ta.traverseSubIds(DB_GLOBAL_TENANT_DB, DB_GLOBAL_ROOT_TENANT, Constants.DB_GLOBAL_TENANT_IDX_DB, when, false, new Function<Object,Boolean>() { @Override public Boolean apply(Object t) { String did = t.toString(); System.out.println("Indexing domain: " + did); task.pushTenant(did); try { // see if there is even such a table in the schema tables.rebuildIndexes(TenantHub.resolveTenant(did), when); return true; } catch (Exception x) { System.out.println("dcRebuildIndexes: Unable to index: " + did); Logger.error("rebuildTenantIndexes error: " + x); } finally { task.popTenant(); } return false; } }); } */ }
28.83871
148
0.690157
5238a58613a8db3c835c1f360ddc51e2e4e179ca
1,687
package finalExamPrep.archive; import java.util.*; import java.util.stream.Collectors; public class P03EnduranceRally { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] names = scan.nextLine().split(" "); Map<String, Double> participants = new LinkedHashMap<>(); for (int i = 0; i < names.length; i++) { participants.put(names[i], (double) ((int) names[i].charAt(0))); } List<Double> zones = Arrays.stream(scan.nextLine().split("\\s+")) .map(Double::parseDouble) .collect(Collectors.toList()); List<Integer> checkpoints = Arrays.stream(scan.nextLine().split("\\s+")) .map(Integer::parseInt) .collect(Collectors.toList()); for (Map.Entry<String, Double> entry : participants.entrySet()) { int lastZone = 0; boolean cantFinish = false; for (int i = 0; i < zones.size(); i++) { if (checkpoints.contains(i)) { entry.setValue(entry.getValue() + zones.get(i)); } else { entry.setValue(entry.getValue() - zones.get(i)); if (entry.getValue() <= 0) { cantFinish = true; lastZone = i; break; } } } if (cantFinish) { System.out.printf("%s - reached %d\n", entry.getKey(), lastZone); } else { System.out.printf("%s - fuel left %.2f\n", entry.getKey(), entry.getValue()); } } } }
34.428571
93
0.489627
296740e901e96334fa477f17e90ae150766201b8
2,621
package com.pivotal.resilient; import java.math.BigDecimal; import java.text.DecimalFormat; public class Trade { long id; long accountId; String asset; long amount; boolean buy; long timestamp; BigDecimal price; private static DecimalFormat priceFormat = new DecimalFormat("##.00"); @Override public String toString() { return new StringBuilder("Trade{") .append(" tradeId=").append(id) .append(" accountId=").append(accountId) .append(" asset=").append(asset) .append(" amount=").append(amount) .append(" buy=").append(buy) .append(" timestamp=").append(timestamp) .append(" ").append(price == null ? " Request" : " Executed @ ") .append(price == null ? "" : priceFormat.format(price)) .append("}").toString(); } public Trade() { } public Trade(long accountId, String asset, long amount, boolean buy, long timestamp) { this.accountId = accountId; this.asset = asset; this.amount = amount; this.buy = buy; this.timestamp = timestamp; } public static Trade buy(long acountId, String asset, long amount, long timestamp) { return new Trade(acountId, asset, amount, true, timestamp); } public static Trade sell(long acountId, String asset, long amount, long timestamp) { return new Trade(acountId, asset, amount, false, timestamp); } public Trade executed(BigDecimal price) { Trade trade = new Trade(accountId, asset, amount, buy, timestamp); trade.id = id; trade.price = price; return trade; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getAccountId() { return accountId; } public void setAccountId(long accountId) { this.accountId = accountId; } public String getAsset() { return asset; } public void setAsset(String asset) { this.asset = asset; } public long getAmount() { return amount; } public void setAmount(long amount) { this.amount = amount; } public boolean isBuy() { return buy; } public void setBuy(boolean buy) { this.buy = buy; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public BigDecimal getPrice() { return price; } }
23.612613
90
0.575734
173fe567655729b7680a39fafb33dddba5e536d1
1,095
/*package seedu.address.logic.commands; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT; import static seedu.address.logic.commands.NoteCommand.MESSAGE_VIEW_SUCCESS; import static seedu.address.logic.parser.CliSyntax.PREFIX_NOTE_VIEW; import java.util.Optional; import org.junit.jupiter.api.Test; import seedu.address.commons.core.index.Index; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.person.Note; public class NoteCommandTest { private Model model = new ModelManager(); private Model expectedModel = new ModelManager(); @Test public void execute_view_note_success() { CommandResult expectedCommandResult = new CommandResult(MESSAGE_VIEW_SUCCESS, false, false, Optional.empty(),false); assertCommandSuccess(new NoteCommand(Index.fromZeroBased(0), PREFIX_NOTE_VIEW, new Note("placeholder")), model, expectedCommandResult, expectedModel); } }*/
37.758621
112
0.779909
342ffffea21303b6f13599de704194814d1e246b
814
package com.pisces.core.primary.expression.calculate; import java.util.Map.Entry; import com.pisces.core.entity.EntityObject; import com.pisces.core.primary.expression.Expression; import com.pisces.core.primary.expression.ExpressionNode; public class BracketCalculate implements Calculate { private Expression value = new Expression(); @Override public Object GetValue(EntityObject entity) { return this.value.getValueImpl(entity); } @Override public int Parse(String str, int index) { Entry<Integer, ExpressionNode> nd = this.value.Create(str, ++index, false); if (nd.getValue() == null) { return -1; } this.value.root = nd.getValue(); return nd.getKey() + 1; } @Override public Class<?> getReturnClass() { return this.value.getReturnClass(); } }
24.666667
78
0.711302
e5b007aca420d2aa7d9c36d768fbe6323cc08880
162
boolean b = true; for(backend.unit.Unit unit: team.getOwnedUnits(gameState.getGrid())){ b = (unit.getMovePoints().getCurrentValue().intValue() == 0); } return b;
32.4
69
0.716049
b0952125ab5cdf5fb2b2ef93962356a790f300ac
27,950
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Lifecycle; import java.io.PrintWriter; import java.util.ArrayList; /** * Entry of an operation on the fragment back stack. */ final class BackStackRecord extends FragmentTransaction implements FragmentManager.BackStackEntry, FragmentManager.OpGenerator { private static final String TAG = FragmentManager.TAG; final FragmentManager mManager; boolean mCommitted; int mIndex = -1; @Override public String toString() { StringBuilder sb = new StringBuilder(128); sb.append("BackStackEntry{"); sb.append(Integer.toHexString(System.identityHashCode(this))); if (mIndex >= 0) { sb.append(" #"); sb.append(mIndex); } if (mName != null) { sb.append(" "); sb.append(mName); } sb.append("}"); return sb.toString(); } public void dump(String prefix, PrintWriter writer) { dump(prefix, writer, true); } public void dump(String prefix, PrintWriter writer, boolean full) { if (full) { writer.print(prefix); writer.print("mName="); writer.print(mName); writer.print(" mIndex="); writer.print(mIndex); writer.print(" mCommitted="); writer.println(mCommitted); if (mTransition != FragmentTransaction.TRANSIT_NONE) { writer.print(prefix); writer.print("mTransition=#"); writer.print(Integer.toHexString(mTransition)); } if (mEnterAnim != 0 || mExitAnim !=0) { writer.print(prefix); writer.print("mEnterAnim=#"); writer.print(Integer.toHexString(mEnterAnim)); writer.print(" mExitAnim=#"); writer.println(Integer.toHexString(mExitAnim)); } if (mPopEnterAnim != 0 || mPopExitAnim !=0) { writer.print(prefix); writer.print("mPopEnterAnim=#"); writer.print(Integer.toHexString(mPopEnterAnim)); writer.print(" mPopExitAnim=#"); writer.println(Integer.toHexString(mPopExitAnim)); } if (mBreadCrumbTitleRes != 0 || mBreadCrumbTitleText != null) { writer.print(prefix); writer.print("mBreadCrumbTitleRes=#"); writer.print(Integer.toHexString(mBreadCrumbTitleRes)); writer.print(" mBreadCrumbTitleText="); writer.println(mBreadCrumbTitleText); } if (mBreadCrumbShortTitleRes != 0 || mBreadCrumbShortTitleText != null) { writer.print(prefix); writer.print("mBreadCrumbShortTitleRes=#"); writer.print(Integer.toHexString(mBreadCrumbShortTitleRes)); writer.print(" mBreadCrumbShortTitleText="); writer.println(mBreadCrumbShortTitleText); } } if (!mOps.isEmpty()) { writer.print(prefix); writer.println("Operations:"); final int numOps = mOps.size(); for (int opNum = 0; opNum < numOps; opNum++) { final Op op = mOps.get(opNum); String cmdStr; switch (op.mCmd) { case OP_NULL: cmdStr="NULL"; break; case OP_ADD: cmdStr="ADD"; break; case OP_REPLACE: cmdStr="REPLACE"; break; case OP_REMOVE: cmdStr="REMOVE"; break; case OP_HIDE: cmdStr="HIDE"; break; case OP_SHOW: cmdStr="SHOW"; break; case OP_DETACH: cmdStr="DETACH"; break; case OP_ATTACH: cmdStr="ATTACH"; break; case OP_SET_PRIMARY_NAV: cmdStr="SET_PRIMARY_NAV"; break; case OP_UNSET_PRIMARY_NAV: cmdStr="UNSET_PRIMARY_NAV";break; case OP_SET_MAX_LIFECYCLE: cmdStr = "OP_SET_MAX_LIFECYCLE"; break; default: cmdStr = "cmd=" + op.mCmd; break; } writer.print(prefix); writer.print(" Op #"); writer.print(opNum); writer.print(": "); writer.print(cmdStr); writer.print(" "); writer.println(op.mFragment); if (full) { if (op.mEnterAnim != 0 || op.mExitAnim != 0) { writer.print(prefix); writer.print("enterAnim=#"); writer.print(Integer.toHexString(op.mEnterAnim)); writer.print(" exitAnim=#"); writer.println(Integer.toHexString(op.mExitAnim)); } if (op.mPopEnterAnim != 0 || op.mPopExitAnim != 0) { writer.print(prefix); writer.print("popEnterAnim=#"); writer.print(Integer.toHexString(op.mPopEnterAnim)); writer.print(" popExitAnim=#"); writer.println(Integer.toHexString(op.mPopExitAnim)); } } } } } BackStackRecord(@NonNull FragmentManager manager) { super(manager.getFragmentFactory(), manager.getHost() != null ? manager.getHost().getContext().getClassLoader() : null); mManager = manager; } @Override public int getId() { return mIndex; } @SuppressWarnings("deprecation") @Override public int getBreadCrumbTitleRes() { return mBreadCrumbTitleRes; } @SuppressWarnings("deprecation") @Override public int getBreadCrumbShortTitleRes() { return mBreadCrumbShortTitleRes; } @SuppressWarnings("deprecation") @Override @Nullable public CharSequence getBreadCrumbTitle() { if (mBreadCrumbTitleRes != 0) { return mManager.getHost().getContext().getText(mBreadCrumbTitleRes); } return mBreadCrumbTitleText; } @SuppressWarnings("deprecation") @Override @Nullable public CharSequence getBreadCrumbShortTitle() { if (mBreadCrumbShortTitleRes != 0) { return mManager.getHost().getContext().getText(mBreadCrumbShortTitleRes); } return mBreadCrumbShortTitleText; } @Override void doAddOp(int containerViewId, Fragment fragment, @Nullable String tag, int opcmd) { super.doAddOp(containerViewId, fragment, tag, opcmd); fragment.mFragmentManager = mManager; } @NonNull @Override public FragmentTransaction remove(@NonNull Fragment fragment) { if (fragment.mFragmentManager != null && fragment.mFragmentManager != mManager) { throw new IllegalStateException("Cannot remove Fragment attached to " + "a different FragmentManager. Fragment " + fragment.toString() + " is already" + " attached to a FragmentManager."); } return super.remove(fragment); } @NonNull @Override public FragmentTransaction hide(@NonNull Fragment fragment) { if (fragment.mFragmentManager != null && fragment.mFragmentManager != mManager) { throw new IllegalStateException("Cannot hide Fragment attached to " + "a different FragmentManager. Fragment " + fragment.toString() + " is already" + " attached to a FragmentManager."); } return super.hide(fragment); } @NonNull @Override public FragmentTransaction show(@NonNull Fragment fragment) { if (fragment.mFragmentManager != null && fragment.mFragmentManager != mManager) { throw new IllegalStateException("Cannot show Fragment attached to " + "a different FragmentManager. Fragment " + fragment.toString() + " is already" + " attached to a FragmentManager."); } return super.show(fragment); } @NonNull @Override public FragmentTransaction detach(@NonNull Fragment fragment) { if (fragment.mFragmentManager != null && fragment.mFragmentManager != mManager) { throw new IllegalStateException("Cannot detach Fragment attached to " + "a different FragmentManager. Fragment " + fragment.toString() + " is already" + " attached to a FragmentManager."); } return super.detach(fragment); } @NonNull @Override public FragmentTransaction setPrimaryNavigationFragment(@Nullable Fragment fragment) { if (fragment != null && fragment.mFragmentManager != null && fragment.mFragmentManager != mManager) { throw new IllegalStateException("Cannot setPrimaryNavigation for Fragment attached to " + "a different FragmentManager. Fragment " + fragment.toString() + " is already" + " attached to a FragmentManager."); } return super.setPrimaryNavigationFragment(fragment); } @NonNull @Override public FragmentTransaction setMaxLifecycle(@NonNull Fragment fragment, @NonNull Lifecycle.State state) { if (fragment.mFragmentManager != mManager) { throw new IllegalArgumentException("Cannot setMaxLifecycle for Fragment not attached to" + " FragmentManager " + mManager); } if (!state.isAtLeast(Lifecycle.State.CREATED)) { throw new IllegalArgumentException("Cannot set maximum Lifecycle below " + Lifecycle.State.CREATED); } return super.setMaxLifecycle(fragment, state); } void bumpBackStackNesting(int amt) { if (!mAddToBackStack) { return; } if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) { Log.v(TAG, "Bump nesting in " + this + " by " + amt); } final int numOps = mOps.size(); for (int opNum = 0; opNum < numOps; opNum++) { final Op op = mOps.get(opNum); if (op.mFragment != null) { op.mFragment.mBackStackNesting += amt; if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) { Log.v(TAG, "Bump nesting of " + op.mFragment + " to " + op.mFragment.mBackStackNesting); } } } } public void runOnCommitRunnables() { if (mCommitRunnables != null) { for (int i = 0; i < mCommitRunnables.size(); i++) { mCommitRunnables.get(i).run(); } mCommitRunnables = null; } } @Override public int commit() { return commitInternal(false); } @Override public int commitAllowingStateLoss() { return commitInternal(true); } @Override public void commitNow() { disallowAddToBackStack(); mManager.execSingleAction(this, false); } @Override public void commitNowAllowingStateLoss() { disallowAddToBackStack(); mManager.execSingleAction(this, true); } int commitInternal(boolean allowStateLoss) { if (mCommitted) throw new IllegalStateException("commit already called"); if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) { Log.v(TAG, "Commit: " + this); LogWriter logw = new LogWriter(TAG); PrintWriter pw = new PrintWriter(logw); dump(" ", pw); pw.close(); } mCommitted = true; if (mAddToBackStack) { mIndex = mManager.allocBackStackIndex(); } else { mIndex = -1; } mManager.enqueueAction(this, allowStateLoss); return mIndex; } /** * Implementation of {@link FragmentManager.OpGenerator}. * This operation is added to the list of pending actions during {@link #commit()}, and * will be executed on the UI thread to run this FragmentTransaction. * * @param records Modified to add this BackStackRecord * @param isRecordPop Modified to add a false (this isn't a pop) * @return true always because the records and isRecordPop will always be changed */ @Override public boolean generateOps(@NonNull ArrayList<BackStackRecord> records, @NonNull ArrayList<Boolean> isRecordPop) { if (FragmentManager.isLoggingEnabled(Log.VERBOSE)) { Log.v(TAG, "Run: " + this); } records.add(this); isRecordPop.add(false); if (mAddToBackStack) { mManager.addBackStackState(this); } return true; } boolean interactsWith(int containerId) { final int numOps = mOps.size(); for (int opNum = 0; opNum < numOps; opNum++) { final Op op = mOps.get(opNum); final int fragContainer = op.mFragment != null ? op.mFragment.mContainerId : 0; if (fragContainer != 0 && fragContainer == containerId) { return true; } } return false; } boolean interactsWith(ArrayList<BackStackRecord> records, int startIndex, int endIndex) { if (endIndex == startIndex) { return false; } final int numOps = mOps.size(); int lastContainer = -1; for (int opNum = 0; opNum < numOps; opNum++) { final Op op = mOps.get(opNum); final int container = op.mFragment != null ? op.mFragment.mContainerId : 0; if (container != 0 && container != lastContainer) { lastContainer = container; for (int i = startIndex; i < endIndex; i++) { BackStackRecord record = records.get(i); final int numThoseOps = record.mOps.size(); for (int thoseOpIndex = 0; thoseOpIndex < numThoseOps; thoseOpIndex++) { final Op thatOp = record.mOps.get(thoseOpIndex); final int thatContainer = thatOp.mFragment != null ? thatOp.mFragment.mContainerId : 0; if (thatContainer == container) { return true; } } } } } return false; } /** * Executes the operations contained within this transaction. The Fragment states will only * be modified if optimizations are not allowed. */ void executeOps() { final int numOps = mOps.size(); for (int opNum = 0; opNum < numOps; opNum++) { final Op op = mOps.get(opNum); final Fragment f = op.mFragment; if (f != null) { f.setNextTransition(mTransition); f.setSharedElementNames(mSharedElementSourceNames, mSharedElementTargetNames); } switch (op.mCmd) { case OP_ADD: f.setNextAnim(op.mEnterAnim); mManager.setExitAnimationOrder(f, false); mManager.addFragment(f); break; case OP_REMOVE: f.setNextAnim(op.mExitAnim); mManager.removeFragment(f); break; case OP_HIDE: f.setNextAnim(op.mExitAnim); mManager.hideFragment(f); break; case OP_SHOW: f.setNextAnim(op.mEnterAnim); mManager.setExitAnimationOrder(f, false); mManager.showFragment(f); break; case OP_DETACH: f.setNextAnim(op.mExitAnim); mManager.detachFragment(f); break; case OP_ATTACH: f.setNextAnim(op.mEnterAnim); mManager.setExitAnimationOrder(f, false); mManager.attachFragment(f); break; case OP_SET_PRIMARY_NAV: mManager.setPrimaryNavigationFragment(f); break; case OP_UNSET_PRIMARY_NAV: mManager.setPrimaryNavigationFragment(null); break; case OP_SET_MAX_LIFECYCLE: mManager.setMaxLifecycle(f, op.mCurrentMaxState); break; default: throw new IllegalArgumentException("Unknown cmd: " + op.mCmd); } if (!mReorderingAllowed && op.mCmd != OP_ADD && f != null) { if (FragmentManager.USE_STATE_MANAGER) { mManager.createOrGetFragmentStateManager(f).moveToExpectedState(); } else { mManager.moveFragmentToExpectedState(f); } } } if (!mReorderingAllowed) { // Added fragments are added at the end to comply with prior behavior. mManager.moveToState(mManager.mCurState, true); } } /** * Reverses the execution of the operations within this transaction. The Fragment states will * only be modified if reordering is not allowed. * * @param moveToState {@code true} if added fragments should be moved to their final state * in ordered transactions */ void executePopOps(boolean moveToState) { for (int opNum = mOps.size() - 1; opNum >= 0; opNum--) { final Op op = mOps.get(opNum); Fragment f = op.mFragment; if (f != null) { f.setNextTransition(FragmentManager.reverseTransit(mTransition)); // Reverse the target and source names for pop operations f.setSharedElementNames(mSharedElementTargetNames, mSharedElementSourceNames); } switch (op.mCmd) { case OP_ADD: f.setNextAnim(op.mPopExitAnim); mManager.setExitAnimationOrder(f, true); mManager.removeFragment(f); break; case OP_REMOVE: f.setNextAnim(op.mPopEnterAnim); mManager.addFragment(f); break; case OP_HIDE: f.setNextAnim(op.mPopEnterAnim); mManager.showFragment(f); break; case OP_SHOW: f.setNextAnim(op.mPopExitAnim); mManager.setExitAnimationOrder(f, true); mManager.hideFragment(f); break; case OP_DETACH: f.setNextAnim(op.mPopEnterAnim); mManager.attachFragment(f); break; case OP_ATTACH: f.setNextAnim(op.mPopExitAnim); mManager.setExitAnimationOrder(f, true); mManager.detachFragment(f); break; case OP_SET_PRIMARY_NAV: mManager.setPrimaryNavigationFragment(null); break; case OP_UNSET_PRIMARY_NAV: mManager.setPrimaryNavigationFragment(f); break; case OP_SET_MAX_LIFECYCLE: mManager.setMaxLifecycle(f, op.mOldMaxState); break; default: throw new IllegalArgumentException("Unknown cmd: " + op.mCmd); } if (!mReorderingAllowed && op.mCmd != OP_REMOVE && f != null) { if (FragmentManager.USE_STATE_MANAGER) { mManager.createOrGetFragmentStateManager(f).moveToExpectedState(); } else { mManager.moveFragmentToExpectedState(f); } } } if (!mReorderingAllowed && moveToState) { mManager.moveToState(mManager.mCurState, true); } } /** * Expands all meta-ops into their more primitive equivalents. This must be called prior to * {@link #executeOps()} or any other call that operations on mOps for forward navigation. * It should not be called for pop/reverse navigation operations. * * <p>Removes all OP_REPLACE ops and replaces them with the proper add and remove * operations that are equivalent to the replace.</p> * * <p>Adds OP_UNSET_PRIMARY_NAV ops to match OP_SET_PRIMARY_NAV, OP_REMOVE and OP_DETACH * ops so that we can restore the old primary nav fragment later. Since callers call this * method in a loop before running ops from several transactions at once, the caller should * pass the return value from this method as the oldPrimaryNav parameter for the next call. * The first call in such a loop should pass the value of * {@link FragmentManager#getPrimaryNavigationFragment()}.</p> * * @param added Initialized to the fragments that are in the mManager.mAdded, this * will be modified to contain the fragments that will be in mAdded * after the execution ({@link #executeOps()}. * @param oldPrimaryNav The tracked primary navigation fragment as of the beginning of * this set of ops * @return the new oldPrimaryNav fragment after this record's ops would be run */ @SuppressWarnings("ReferenceEquality") Fragment expandOps(ArrayList<Fragment> added, Fragment oldPrimaryNav) { for (int opNum = 0; opNum < mOps.size(); opNum++) { final Op op = mOps.get(opNum); switch (op.mCmd) { case OP_ADD: case OP_ATTACH: added.add(op.mFragment); break; case OP_REMOVE: case OP_DETACH: { added.remove(op.mFragment); if (op.mFragment == oldPrimaryNav) { mOps.add(opNum, new Op(OP_UNSET_PRIMARY_NAV, op.mFragment)); opNum++; oldPrimaryNav = null; } } break; case OP_REPLACE: { final Fragment f = op.mFragment; final int containerId = f.mContainerId; boolean alreadyAdded = false; for (int i = added.size() - 1; i >= 0; i--) { final Fragment old = added.get(i); if (old.mContainerId == containerId) { if (old == f) { alreadyAdded = true; } else { // This is duplicated from above since we only make // a single pass for expanding ops. Unset any outgoing primary nav. if (old == oldPrimaryNav) { mOps.add(opNum, new Op(OP_UNSET_PRIMARY_NAV, old)); opNum++; oldPrimaryNav = null; } final Op removeOp = new Op(OP_REMOVE, old); removeOp.mEnterAnim = op.mEnterAnim; removeOp.mPopEnterAnim = op.mPopEnterAnim; removeOp.mExitAnim = op.mExitAnim; removeOp.mPopExitAnim = op.mPopExitAnim; mOps.add(opNum, removeOp); added.remove(old); opNum++; } } } if (alreadyAdded) { mOps.remove(opNum); opNum--; } else { op.mCmd = OP_ADD; added.add(f); } } break; case OP_SET_PRIMARY_NAV: { // It's ok if this is null, that means we will restore to no active // primary navigation fragment on a pop. mOps.add(opNum, new Op(OP_UNSET_PRIMARY_NAV, oldPrimaryNav)); opNum++; // Will be set by the OP_SET_PRIMARY_NAV we inserted before when run oldPrimaryNav = op.mFragment; } break; } } return oldPrimaryNav; } /** * Removes fragments that are added or removed during a pop operation. * * @param added Initialized to the fragments that are in the mManager.mAdded, this * will be modified to contain the fragments that will be in mAdded * after the execution ({@link #executeOps()}. * @param oldPrimaryNav The tracked primary navigation fragment as of the beginning of * this set of ops * @return the new oldPrimaryNav fragment after this record's ops would be popped */ Fragment trackAddedFragmentsInPop(ArrayList<Fragment> added, Fragment oldPrimaryNav) { for (int opNum = mOps.size() - 1; opNum >= 0; opNum--) { final Op op = mOps.get(opNum); switch (op.mCmd) { case OP_ADD: case OP_ATTACH: added.remove(op.mFragment); break; case OP_REMOVE: case OP_DETACH: added.add(op.mFragment); break; case OP_UNSET_PRIMARY_NAV: oldPrimaryNav = op.mFragment; break; case OP_SET_PRIMARY_NAV: oldPrimaryNav = null; break; case OP_SET_MAX_LIFECYCLE: op.mCurrentMaxState = op.mOldMaxState; break; } } return oldPrimaryNav; } boolean isPostponed() { for (int opNum = 0; opNum < mOps.size(); opNum++) { final Op op = mOps.get(opNum); if (isFragmentPostponed(op)) { return true; } } return false; } void setOnStartPostponedListener(Fragment.OnStartEnterTransitionListener listener) { for (int opNum = 0; opNum < mOps.size(); opNum++) { final Op op = mOps.get(opNum); if (isFragmentPostponed(op)) { op.mFragment.setOnStartEnterTransitionListener(listener); } } } private static boolean isFragmentPostponed(Op op) { final Fragment fragment = op.mFragment; return fragment != null && fragment.mAdded && fragment.mView != null && !fragment.mDetached && !fragment.mHidden && fragment.isPostponed(); } @Override @Nullable public String getName() { return mName; } @Override public boolean isEmpty() { return mOps.isEmpty(); } }
40.390173
100
0.54068
d90793fb3c7dce1bdfe73738c077c1a9aadf5d42
1,586
/* */ package de.friedrichs.malteser.data.entity; import org.junit.Test; import static org.junit.Assert.*; /** * * @author AFR */ public class FahrgastTest { public FahrgastTest() { } @Test public void testGetAnschrift() { System.out.println("getAnschrift"); Fahrgast f1 = new Fahrgast(); f1.setAdresszusatz("Zusatz"); f1.setStrasse("Strasse 13"); f1.setPlz("12345"); f1.setOrt("Ort"); Fahrgast f2 = new Fahrgast(); f2.setStrasse("Strasse 13"); f2.setPlz("12345"); f2.setOrt("Ort"); Fahrgast f3 = new Fahrgast(); f3.setPlz("12345"); f3.setOrt("Ort"); Fahrgast f4 = new Fahrgast(); f4.setStrasse("Strasse 13"); f4.setPlz("12345"); Fahrgast f5 = new Fahrgast(); f5.setStrasse("Strasse 13"); f5.setOrt("Ort"); Fahrgast f6 = new Fahrgast(); f6.setOrt("Ort"); String expF1 = "Zusatz, Strasse 13, 12345 Ort"; String expF2 = "Strasse 13, 12345 Ort"; String expF3 = "12345 Ort"; String expF4 = "Strasse 13, 12345"; String expF5 = "Strasse 13, Ort"; String expF6 = "Ort"; assertEquals(expF1, f1.getAnschrift()); assertEquals(expF2, f2.getAnschrift()); assertEquals(expF3, f3.getAnschrift()); assertEquals(expF4, f4.getAnschrift()); assertEquals(expF5, f5.getAnschrift()); assertEquals(expF6, f6.getAnschrift()); } }
24.4
55
0.540984
d6525878981f11aeea2788f6491a7a074ba6c73c
810
package com.GH.king; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by alex on 2016/1/25. */ @Component public class CrosConfig implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Methods","GET,PUT,DELETE,POST"); chain.doFilter(req, res); } @Override public void destroy() {} @Override public void init(FilterConfig arg0) throws ServletException {} }
27.931034
82
0.704938
16800409e30d321fde2b6fd9e6b58933e2e72692
4,378
package com.iboxapp.ibox.adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.iboxapp.ibox.R; import java.io.InputStream; import java.util.List; /** * Created by gongchen on 2016/4/20. */ public class TopThingsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private LayoutInflater mLayoutInflater; private Context context; private OnItemClickListener mOnItemClickListener; private String[] titles; private List<String> datas; private List<Integer> mDatasImg; public enum ITEM_TYPE { ITEM1 } public TopThingsRecyclerViewAdapter(Context context, List data, List<Integer> imgs, String[] titles) { this.titles = titles; this.context = context; this.datas = data; this.mDatasImg = imgs; mLayoutInflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ItemViewHolder(mLayoutInflater.inflate(R.layout.top_things_cardview, parent, false)); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { ((ItemViewHolder) holder).mTextViewPrice.setText(titles[position]); ((ItemViewHolder) holder).mTextViewName.setText(getItem(position)); ((ItemViewHolder) holder).mImageView.setImageBitmap(readBitMap(context, mDatasImg.get(position))); if(mOnItemClickListener != null) { /** * 这里加了判断,itemViewHolder.itemView.hasOnClickListeners() * 目的是减少对象的创建,如果已经为view设置了click监听事件,就不用重复设置了 * 不然每次调用onBindViewHolder方法,都会创建两个监听事件对象,增加了内存的开销 */ if(!holder.itemView.hasOnClickListeners()) { Log.e("ListAdapter", "setOnClickListener"); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getPosition(); mOnItemClickListener.onItemClick(v, pos); // mOnItemClickListener.onItemLikeClick(v,pos); } }); } } } @Override public int getItemViewType(int position) { return ITEM_TYPE.ITEM1.ordinal(); } @Override public int getItemCount() { return titles == null ? 0 : titles.length; } private String getItem(int position) { return datas.get(position); } public static class ItemViewHolder extends RecyclerView.ViewHolder { public TextView mTextViewPrice; public TextView mTextViewName; public ImageView mImageView; public ItemViewHolder(View itemView) { super(itemView); mTextViewPrice = (TextView) itemView.findViewById(R.id.text_card_price); mTextViewName = (TextView) itemView.findViewById(R.id.text_card_name); mImageView = (ImageView) itemView.findViewById(R.id.image_card_top10); } } /** * 处理item的点击事件 */ public interface OnItemClickListener { public void onItemClick(View view, int position); // public void onItemLikeClick(View view, int position); // public void onItemBuyClick(View view, int position); // public void onItemShareClick(View view, int position); } //添加点击事件 public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) { this.mOnItemClickListener = mOnItemClickListener; } /** * 以最省内存的方式读取本地资源的图片 * @param context * @param resId * @return */ public static Bitmap readBitMap(Context context, int resId){ BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //获取资源图片 InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); } }
32.42963
106
0.662631
190d9b28283db2fa239888e6ee02bb0af16624d3
546
package com.github.ayltai.newspaper.view; import javax.annotation.Nonnull; import android.app.Activity; import androidx.annotation.NonNull; import dagger.Module; import dagger.Provides; @Module public final class RouterModule { @Nonnull @NonNull private final Activity activity; public RouterModule(@Nonnull @NonNull @lombok.NonNull final Activity activity) { this.activity = activity; } @Nonnull @NonNull @Provides Router provideRouter() { return new MainRouter(this.activity); } }
18.827586
84
0.714286
9ad7f24f86e6a10e9f065894134accb8326dcf1f
18,628
/* * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.util; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import javax.servlet.http.Cookie; import org.apache.naming.Util; import org.glassfish.grizzly.http.util.ByteChunk; import org.glassfish.grizzly.utils.Charsets; /** * General purpose request parsing and encoding utility methods. * * @author Craig R. McClanahan * @author Tim Tye * @version $Revision: 1.4 $ $Date: 2006/12/12 20:43:07 $ */ public final class RequestUtil { private static final String SESSION_VERSION_SEPARATOR = ":"; /** * Encode a cookie as per RFC 2109. The resulting string can be used * as the value for a <code>Set-Cookie</code> header. * * @param cookie The cookie to encode. * @return A string following RFC 2109. */ public static String encodeCookie(Cookie cookie) { StringBuilder buf = new StringBuilder( cookie.getName() ); buf.append("="); buf.append(cookie.getValue()); if (cookie.getComment() != null) { buf.append("; Comment=\""); buf.append(cookie.getComment()); buf.append("\""); } if (cookie.getDomain() != null) { buf.append("; Domain=\""); buf.append(cookie.getDomain()); buf.append("\""); } if (cookie.getMaxAge() >= 0) { buf.append("; Max-Age=\""); buf.append(cookie.getMaxAge()); buf.append("\""); } if (cookie.getPath() != null) { buf.append("; Path=\""); buf.append(cookie.getPath()); buf.append("\""); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.getVersion() > 0) { buf.append("; Version=\""); buf.append(cookie.getVersion()); buf.append("\""); } return (buf.toString()); } /** * Normalize a relative URI path that may have relative values ("/./", * "/../", and so on ) it it. <strong>WARNING</strong> - This method is * useful only for normalizing application-generated paths. It does not * try to perform security checks for malicious input. * * @param path Relative path to be normalized */ public static String normalize(String path) { return normalize(path, true); } /** * Normalize a relative URI path that may have relative values ("/./", * "/../", and so on ) it it. <strong>WARNING</strong> - This method is * useful only for normalizing application-generated paths. It does not * try to perform security checks for malicious input. * * @param path Relative path to be normalized * @param replaceBackSlash Should '\\' be replaced with '/' */ public static String normalize(String path, boolean replaceBackSlash) { // Implementation has been moved to org.apache.naming.Util // so that it may be accessed by code in web-naming return Util.normalize(path, replaceBackSlash); } /** * Parse the character encoding from the specified content type header. * If the content type is null, or there is no explicit character encoding, * <code>null</code> is returned. * * @param contentType a content type header */ public static String parseCharacterEncoding(String contentType) { if (contentType == null) return (null); int start = contentType.indexOf("charset="); if (start < 0) return (null); String encoding = contentType.substring(start + 8); int end = encoding.indexOf(';'); if (end >= 0) encoding = encoding.substring(0, end); encoding = encoding.trim(); if ((encoding.length() > 2) && (encoding.startsWith("\"")) && (encoding.endsWith("\""))) encoding = encoding.substring(1, encoding.length() - 1); return (encoding.trim()); } /** * Parse a cookie header into an array of cookies according to RFC 2109. * * @param header Value of an HTTP "Cookie" header */ public static Cookie[] parseCookieHeader(String header) { if ((header == null) || (header.length() < 1)) return (new Cookie[0]); ArrayList<Cookie> cookies = new ArrayList<Cookie>(); while (header.length() > 0) { int semicolon = header.indexOf(';'); if (semicolon < 0) semicolon = header.length(); if (semicolon == 0) break; String token = header.substring(0, semicolon); if (semicolon < header.length()) header = header.substring(semicolon + 1); else header = ""; try { int equals = token.indexOf('='); if (equals > 0) { String name = token.substring(0, equals).trim(); String value = token.substring(equals+1).trim(); cookies.add(new Cookie(name, value)); } } catch (Throwable e) { // Ignore } } return cookies.toArray(new Cookie[cookies.size()]); } /** * Append request parameters from the specified String to the specified * Map. It is presumed that the specified Map is not accessed from any * other thread, so no synchronization is performed. * <p> * <strong>IMPLEMENTATION NOTE</strong>: URL decoding is performed * individually on the parsed name and value elements, rather than on * the entire query string ahead of time, to properly deal with the case * where the name or value includes an encoded "=" or "&" character * that would otherwise be interpreted as a delimiter. * * @param map Map that accumulates the resulting parameters * @param data Input string containing request parameters * @param encoding The name of a supported charset used to encode * * @exception IllegalArgumentException if the data is malformed */ public static void parseParameters(Map<String, String[]> map, String data, String encoding) throws UnsupportedEncodingException { if ((data != null) && (data.length() > 0)) { // use the specified encoding to extract bytes out of the // given string so that the encoding is not lost. If an // encoding is not specified, let it use platform default byte[] bytes = null; try { if (encoding == null) { bytes = data.getBytes(Charset.defaultCharset()); } else { bytes = data.getBytes(Charsets.lookupCharset(encoding)); } } catch (UnsupportedCharsetException uee) { } parseParameters(map, bytes, encoding); } } /** * Decode and return the specified URL-encoded String. * When the byte array is converted to a string, the system default * character encoding is used... This may be different than some other * servers. * * @param str The url-encoded string * * @exception IllegalArgumentException if a '%' character is not followed * by a valid 2-digit hexadecimal number */ public static String urlDecode(String str) { // Implementation has been moved to org.apache.naming.Util // so that it may be accessed by code in war-util return Util.urlDecode(str); } /** * Decode and return the specified URL-encoded String. * * @param str The url-encoded string * @param enc The encoding to use; if null, the default encoding is used * @exception IllegalArgumentException if a '%' character is not followed * by a valid 2-digit hexadecimal number */ public static String urlDecode(String str, String enc) { // Implementation has been moved to org.apache.naming.Util // so that it may be accessed by code in war-util return Util.urlDecode(str, enc); } /** * Decode and return the specified URL-encoded byte array. * * @param bytes The url-encoded byte array * @exception IllegalArgumentException if a '%' character is not followed * by a valid 2-digit hexadecimal number */ public static String urlDecode(byte[] bytes) { // Implementation has been moved to org.apache.naming.Util // so that it may be accessed by code in war-util return Util.urlDecode(bytes); } /** * Decode and return the specified URL-encoded byte array. * * @param bytes The url-encoded byte array * @param enc The encoding to use; if null, the default encoding is used * @exception IllegalArgumentException if a '%' character is not followed * by a valid 2-digit hexadecimal number */ public static String urlDecode(byte[] bytes, String enc) { // Implementation has been moved to org.apache.naming.Util // so that it may be accessed by code in war-util return Util.urlDecode(bytes, enc); } /** * Decode (in place) the specified URL-encoded byte chunk, and optionally * return the decoded result as a String * * @param bc The URL-encoded byte chunk to be decoded in place * @param toString true if the decoded result is to be returned as a * String, false otherwise * * @return The decoded result in String form, if <code>toString</code> * is true, or null otherwise * * @exception IllegalArgumentException if a '%' character is not followed * by a valid 2-digit hexadecimal number */ public static String urlDecode(ByteChunk bc, boolean toString) { if (bc == null) { return (null); } byte[] bytes = bc.getBytes(); if (bytes == null) { return (null); } int ix = bc.getStart(); int end = bc.getEnd(); int ox = ix; while (ix < end) { byte b = bytes[ix++]; // Get byte to test if (b == '+') { b = (byte)' '; } else if (b == '%') { b = (byte) ((Util.convertHexDigit(bytes[ix++]) << 4) + Util.convertHexDigit(bytes[ix++])); } bytes[ox++] = b; } bc.setEnd(ox); if (toString) { return bc.toString(); } else { return null; } } /** * Put name value pair in map. * * Put name and value pair in map. When name already exist, add value * to array of values. */ private static void putMapEntry( Map<String, String[]> map, String name, String value) { String[] newValues = null; String[] oldValues = map.get(name); if (oldValues == null) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[oldValues.length] = value; } map.put(name, newValues); } /** * Append request parameters from the specified String to the specified * Map. It is presumed that the specified Map is not accessed from any * other thread, so no synchronization is performed. * <p> * <strong>IMPLEMENTATION NOTE</strong>: URL decoding is performed * individually on the parsed name and value elements, rather than on * the entire query string ahead of time, to properly deal with the case * where the name or value includes an encoded "=" or "&" character * that would otherwise be interpreted as a delimiter. * * NOTE: byte array data is modified by this method. Caller beware. * * @param map Map that accumulates the resulting parameters * @param data Input string containing request parameters * @param encoding Encoding to use for converting hex * * @exception UnsupportedEncodingException if the data is malformed */ public static void parseParameters(Map<String, String[]> map, byte[] data, String encoding) throws UnsupportedEncodingException { if (data != null && data.length > 0) { int pos = 0; int ix = 0; int ox = 0; String key = null; String value = null; while (ix < data.length) { byte c = data[ix++]; switch ((char) c) { case '&': value = new String(data, 0, ox, Charsets.lookupCharset(encoding)); if (key != null) { putMapEntry(map, key, value); key = null; } ox = 0; break; case '=': if (key == null) { key = new String(data, 0, ox, Charsets.lookupCharset(encoding)); ox = 0; } else { data[ox++] = c; } break; case '+': data[ox++] = (byte)' '; break; case '%': data[ox++] = (byte)((Util.convertHexDigit(data[ix++]) << 4) + Util.convertHexDigit(data[ix++])); break; default: data[ox++] = c; } } //The last value does not end in '&'. So save it now. if (key != null) { value = new String(data, 0, ox, Charsets.lookupCharset(encoding)); putMapEntry(map, key, value); } } } /** * Parses the given session version string into its components. * * @param sessionVersion The session version string to parse * * @return The mappings from context paths to session version numbers * that were parsed from the given session version string */ public static final HashMap<String, String> parseSessionVersionString( String sessionVersion) { if (sessionVersion == null) { return null; } StringTokenizer st = new StringTokenizer(sessionVersion, SESSION_VERSION_SEPARATOR); HashMap<String, String> result = new HashMap<String, String>(st.countTokens()); while (st.hasMoreTokens()) { String hexPath = st.nextToken(); if (st.hasMoreTokens()) { try { String contextPath = new String( HexUtils.convert(hexPath), Charsets.UTF8_CHARSET); result.put(contextPath, st.nextToken()); } catch(UnsupportedCharsetException ex) { //should not be here throw new IllegalArgumentException(ex); } } } return result; } /** * Creates the string representation for the given context path to * session version mappings. * * <p>The returned string will be used as the value of a * JSESSIONIDVERSION cookie or jsessionidversion URI parameter, depending * on the configured session tracking mode. * * @param sessionVersions Context path to session version mappings * * @return The resulting string representation, to be used as the value * of a JSESSIONIDVERSION cookie or jsessionidversion URI parameter */ public static String createSessionVersionString(Map<String, String> sessionVersions) { if (sessionVersions == null) { return null; } StringBuilder sb = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> e : sessionVersions.entrySet()) { if (first) { first = false; } else { sb.append(':'); } String contextPath = e.getKey(); // encode so that there is no / or %2F try { sb.append(new String(HexUtils.convert(contextPath.getBytes(Charsets.UTF8_CHARSET)))); } catch(UnsupportedCharsetException ex) { //should not be here throw new IllegalArgumentException(ex); } sb.append(SESSION_VERSION_SEPARATOR); sb.append(e.getValue()); } return sb.toString(); } /** * This is a convenient API which wraps around the one in Grizzly and throws * checked java.io.UnsupportedEncodingException instead of * unchecked java.nio.charset.UnsupportedCharsetException. * cf. String.getBytes(String charset) throws UnsupportedEncodingException * * @exception UnsupportedEncodingException */ public static Charset lookupCharset(String enc) throws UnsupportedEncodingException { Charset charset = null; Throwable throwable = null; try { charset = Charsets.lookupCharset(enc); } catch(Throwable t) { throwable = t; } if (charset == null) { UnsupportedEncodingException uee = new UnsupportedEncodingException(); if (throwable != null) { uee.initCause(throwable); } throw uee; } return charset; } }
34.753731
101
0.5707
3b0333b7f3f05265eef9f1912a88234301276095
5,429
package com.dada.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Toast; import com.dada.android.db.Cark; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import cn.bmob.v3.listener.FindListener; import static android.widget.Toast.*; /** * Created by asus1 on 2017/11/27. */ public class MakeMenu extends AppCompatActivity { private Button show, find; private SeekBar seekBar; private String type; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shouye); initNews(); setListener(); BmobFile bmobfile =new BmobFile("xxx.png","","http://bmob-cdn-15323.b0.upaiyun.com/2017/11/29/cc9ac3e340cbcd098056465c6e35369f.png"); // bmobfile.download(new DownloadFileListener() { // @Override // public void done(String s, BmobException e) { // if (e==null){ // String url=s; // // Toast.makeText(MakeMenu.this, "下载成功,保存路径", Toast.LENGTH_SHORT).show(); // }else { // Toast.makeText(MakeMenu.this, "下载成功", Toast.LENGTH_SHORT).show(); // } // } // // @Override // public void onProgress(Integer integer, long l) { // Log.i("bmob", "下载进度:" + integer + "," +l); // } // }); BmobQuery<Cark> query1 = new BmobQuery<Cark>(); } public void downloadFile(final BmobFile file) { //允许设置下载文件的存储路径,默认下载文件的目录为:context.getApplicationContext().getCacheDir()+"/bmob/" file.download(new DownloadFileListener() { @Override public void onStart() { Toast.makeText(MakeMenu.this, "开始下载:", Toast.LENGTH_SHORT).show(); } @Override public void done(String savePath, BmobException e) { if (e == null) { String s=file.getFileUrl(); Toast.makeText(MakeMenu.this, "下载成功,保存路径", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MakeMenu.this, "下载成功", Toast.LENGTH_SHORT).show(); } } @Override public void onProgress(Integer value, long newworkSpeed) { Log.i("bmob", "下载进度:" + value + "," + newworkSpeed); } }); } public void initNews() { show = (Button) findViewById(R.id.button_show); seekBar = (SeekBar) findViewById(R.id.seekbar); find = (Button) findViewById(R.id.button_find); } public void setListener() { ButtonListener buttonListener = new ButtonListener(); show.setOnClickListener(buttonListener); find.setOnClickListener(buttonListener); SeekBarListener seekBarListener = new SeekBarListener(); seekBar.setOnSeekBarChangeListener(seekBarListener); } } class ButtonListener implements OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_show: Toast.makeText(MainActivity.mainActivity, "show", Toast.LENGTH_SHORT).show(); break; case R.id.button_find: final MakeMenu makeMenu = new MakeMenu(); BmobQuery<Cark> query = new BmobQuery<Cark>(); query.findObjects(new FindListener<Cark>() { @Override public void done(List<Cark> list, BmobException e) { if (e == null) { for (Cark cark : list) { BmobFile file = cark.getDrawable(); if (file != null) { makeMenu.downloadFile(file); Log.d("MakeMenu", "Find!!!"); } } } else { Toast.makeText(makeMenu, "查询失败", Toast.LENGTH_SHORT).show(); } } }); break; } } } class SeekBarListener implements OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { Log.d("MakeMenu", seekBar.getProgress() + "2333"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { Log.d("MakeMenu", seekBar.getProgress() + "3444"); } @Override public void onStopTrackingTouch(SeekBar seekBar) { Toast.makeText(MainActivity.mainActivity, seekBar.getProgress() + "", LENGTH_SHORT).show(); } }
32.508982
141
0.581691
9a10c59ea8ab40f7f885f7c72356ca8284a1e753
600
package com.xiao.jvm.classLoader; /** * @author Malone Xiao * @ClassName TestSon.java * @Description * @createTime 2021年05月25日 23:39:00 */ public class TestSon { public static void main(String[] args) { Father father = new Son(); father.print(); } } class Father { int i= 10; Father() { this.print(); i = 20; } public void print() { System.out.println(i); } } class Son extends Father { int i = 30; Son() { this.print(); i = 40; } public void print() { System.out.println(i); } }
16.216216
44
0.533333
c2cd6f24ccb977c8d626d5a9ea8f84c9416a7e1a
1,747
/* * Copyright (c) 2018-present PowerFlows.org - all rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powerflows.dmn.engine.model.evaluation.result; import lombok.ToString; import org.powerflows.dmn.engine.model.builder.AbstractBuilder; import java.io.Serializable; /** * Represents entry evaluation result. */ @ToString public class EntryResult implements Serializable { private static final long serialVersionUID = 1; private String name; private Serializable value; private EntryResult() { } public String getName() { return name; } public Serializable getValue() { return value; } public static Builder builder() { return new Builder(); } public static class Builder extends AbstractBuilder<EntryResult> { private Builder() { } @Override protected void initProduct() { this.product = new EntryResult(); } public Builder name(String name) { this.product.name = name; return this; } public Builder value(Serializable value) { this.product.value = value; return this; } } }
23.608108
75
0.661133
bda65ce75c6d380a0c59a1c0f4f5f8ed5c130e63
14,714
package in.elango.tamillearning; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; public class TamilmeiquizActivity extends Activity { Resources res; int gamePoints = 0; String timeText = null; String pointsText = null; Button pointButton = null; Typeface typeface = null; String POINTS_TEXT = null; String TIME_REMAINING = null; Context con= null; Button questionButton = null; Button answerButton_1 = null; Button answerButton_2 = null; Button answerButton_3 = null; Button answerButton_4 = null; int screenHeight = 0; int screenWidth = 0; int heightMultiple = 0; int widthMultiple = 0; CountDownTimer countDown; int pointsTextFontSize = 0; int buttonsTextFontSize = 0; MediaPlayer mediaPlay = null; int randomNumUirMeiReference; final Handler handler = new Handler(); public Integer[] audio_files = { R.raw.u1, R.raw.u2, R.raw.u3, R.raw.u4, R.raw.u5, R.raw.u6, R.raw.u7, R.raw.u8, R.raw.u9, R.raw.u10, R.raw.u11, R.raw.u12, R.raw.m1, R.raw.m2, R.raw.m3, R.raw.m4, R.raw.m5, R.raw.m6, R.raw.m7, R.raw.m8, R.raw.m9, R.raw.m10, R.raw.m11, R.raw.m12, R.raw.m13, R.raw.m14, R.raw.m15, R.raw.m16, R.raw.m17, R.raw.m18, R.raw.m1u1, R.raw.m2u1, R.raw.m3u1, R.raw.m4u1, R.raw.m5u1, R.raw.m6u1, R.raw.m7u1, R.raw.m8u1, R.raw.m9u1, R.raw.m10u1, R.raw.m11u1, R.raw.m12u1, R.raw.m13u1, R.raw.m14u1, R.raw.m15u1, R.raw.m16u1, R.raw.m17u1, R.raw.m18u1, R.raw.m1u2, R.raw.m2u2, R.raw.m3u2, R.raw.m4u2, R.raw.m5u2, R.raw.m6u2, R.raw.m7u2, R.raw.m8u2, R.raw.m9u2, R.raw.m10u2, R.raw.m11u2, R.raw.m12u2, R.raw.m13u2, R.raw.m14u2, R.raw.m15u2, R.raw.m16u2, R.raw.m17u2, R.raw.m18u2, R.raw.m1u3, R.raw.m2u3, R.raw.m3u3, R.raw.m4u3, R.raw.m5u3, R.raw.m6u3, R.raw.m7u3, R.raw.m8u3, R.raw.m9u3, R.raw.m10u3, R.raw.m11u3, R.raw.m12u3, R.raw.m13u3, R.raw.m14u3, R.raw.m15u3, R.raw.m16u3, R.raw.m17u3, R.raw.m18u3, R.raw.m1u4, R.raw.m2u4, R.raw.m3u4, R.raw.m4u4, R.raw.m5u4, R.raw.m6u4, R.raw.m7u4, R.raw.m8u4, R.raw.m9u4, R.raw.m10u4, R.raw.m11u4, R.raw.m12u4, R.raw.m13u4, R.raw.m14u4, R.raw.m15u4, R.raw.m16u4, R.raw.m17u4, R.raw.m18u4, R.raw.m1u5, R.raw.m2u5, R.raw.m3u5, R.raw.m4u5, R.raw.m5u5, R.raw.m6u5, R.raw.m7u5, R.raw.m8u5, R.raw.m9u5, R.raw.m10u5, R.raw.m11u5, R.raw.m12u5, R.raw.m13u5, R.raw.m14u5, R.raw.m15u5, R.raw.m16u5, R.raw.m17u5, R.raw.m18u5, R.raw.m1u6, R.raw.m2u6, R.raw.m3u6, R.raw.m4u6, R.raw.m5u6, R.raw.m6u6, R.raw.m7u6, R.raw.m8u6, R.raw.m9u6, R.raw.m10u6, R.raw.m11u6, R.raw.m12u6, R.raw.m13u6, R.raw.m14u6, R.raw.m15u6, R.raw.m16u6, R.raw.m17u6, R.raw.m18u6, R.raw.m1u7, R.raw.m2u7, R.raw.m3u7, R.raw.m4u7, R.raw.m5u7, R.raw.m6u7, R.raw.m7u7, R.raw.m8u7, R.raw.m9u7, R.raw.m10u7, R.raw.m11u7, R.raw.m12u7, R.raw.m13u7, R.raw.m14u7, R.raw.m15u7, R.raw.m16u7, R.raw.m17u7, R.raw.m18u7, R.raw.m1u8, R.raw.m2u8, R.raw.m3u8, R.raw.m4u8, R.raw.m5u8, R.raw.m6u8, R.raw.m7u8, R.raw.m8u8, R.raw.m9u8, R.raw.m10u8, R.raw.m11u8, R.raw.m12u8, R.raw.m13u8, R.raw.m14u8, R.raw.m15u8, R.raw.m16u8, R.raw.m17u8, R.raw.m18u8, R.raw.m1u9, R.raw.m2u9, R.raw.m3u9, R.raw.m4u9, R.raw.m5u9, R.raw.m6u9, R.raw.m7u9, R.raw.m8u9, R.raw.m9u9, R.raw.m10u9, R.raw.m11u9, R.raw.m12u9, R.raw.m13u9, R.raw.m14u9, R.raw.m15u9, R.raw.m16u9, R.raw.m17u9, R.raw.m18u9, R.raw.m1u10, R.raw.m2u10, R.raw.m3u10, R.raw.m4u10, R.raw.m5u10, R.raw.m6u10, R.raw.m7u10, R.raw.m8u10, R.raw.m9u10, R.raw.m10u10, R.raw.m11u10, R.raw.m12u10, R.raw.m13u10, R.raw.m14u10, R.raw.m15u10, R.raw.m16u10, R.raw.m17u10, R.raw.m18u10, R.raw.m1u11, R.raw.m2u11, R.raw.m3u11, R.raw.m4u11, R.raw.m5u11, R.raw.m6u11, R.raw.m7u11, R.raw.m8u11, R.raw.m9u11, R.raw.m10u11, R.raw.m11u11, R.raw.m12u11, R.raw.m13u11, R.raw.m14u11, R.raw.m15u11, R.raw.m16u11, R.raw.m17u11, R.raw.m18u11, R.raw.m1u12, R.raw.m2u12, R.raw.m3u12, R.raw.m4u12, R.raw.m5u12, R.raw.m6u12, R.raw.m7u12, R.raw.m8u12, R.raw.m9u12, R.raw.m10u12, R.raw.m11u12, R.raw.m12u12, R.raw.m13u12, R.raw.m14u12, R.raw.m15u12, R.raw.m16u12, R.raw.m17u12, R.raw.m18u12 }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tamiluirmeilayout); setVolumeControlStream(AudioManager.STREAM_MUSIC); //Remove title bar //this.requestWindowFeature(Window.FEATURE_NO_TITLE); initializeSettings(); initDisplay(); initTamilQuizLetter(); initRefreshDisplayText(); releaseMediaPlayers(); mediaPlay = MediaPlayer.create(this, R.raw.background_score); //mediaPlay.setLooping(true); mediaPlay.start(); // count down for 100 seconds // Interval of 2 second } void initDisplay() { pointButton = (Button) findViewById(R.id.pointsbutton); pointButton.setHeight(heightMultiple); pointButton.setTypeface(typeface); pointButton.setTextSize(pointsTextFontSize ); pointsText = getString(R.string.points); pointsText = ReEncodeTamil.unicode2tsc(POINTS_TEXT) + " " + gamePoints; // pointsText = ReEncodeTamil.convertBaminiTamilString(pointsText); // pointsText = ReEncodeTamil.unicode2tsc(pointsText + " " + gamePoints // + timeText); // pointButton.setText(pointsText); pointButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something in response to button click } }); // ============================================== questionButton = (Button) findViewById(R.id.questionbutton); questionButton.setHeight(heightMultiple * 2); questionButton.setTypeface(typeface); questionButton.setTextSize(pointsTextFontSize ); questionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something in response to button click releaseMediaPlayers(); mediaPlay = MediaPlayer.create(getBaseContext(),audio_files[randomNumUirMeiReference]); mediaPlay.start(); } }); // ============================================== answerButton_1 = (Button) findViewById(R.id.answerbutton_1); answerButton_1.setHeight(heightMultiple); answerButton_1.setTextSize(buttonsTextFontSize ); ViewGroup.LayoutParams answerButton_1_params = answerButton_1 .getLayoutParams(); answerButton_1_params.width = widthMultiple; answerButton_1.setLayoutParams(answerButton_1_params); answerButton_1.setTypeface(typeface); answerButton_1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something in response to button click //Log.e("Elango", "Button 1 clicked"); if (TamilLetters.getQuizOptions()[0].equals(TamilLetters .getUriMeiLetter())) { //Log.e("Elango", "Answer 1 Correct"); playSuccessSound(); refreshTamilQuizLetter(); } else { answerButton_1.setBackgroundColor(Color .parseColor("#ff0000")); } } }); // ============================================== answerButton_2 = (Button) findViewById(R.id.answerbutton_2); answerButton_2.setHeight(heightMultiple); answerButton_2.setTextSize(buttonsTextFontSize ); ViewGroup.LayoutParams answerButton_2_params = answerButton_2 .getLayoutParams(); answerButton_2_params.width = widthMultiple; answerButton_2.setLayoutParams(answerButton_2_params); answerButton_2.setTypeface(typeface); answerButton_2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Log.e("Elango", "Button 2 clicked"); if (TamilLetters.getQuizOptions()[1].equals(TamilLetters .getUriMeiLetter())) { //Log.e("Elango", "Answer 2 Correct"); playSuccessSound(); refreshTamilQuizLetter(); } else { answerButton_2.setBackgroundColor(Color .parseColor("#ff0000")); } } }); // ============================================== answerButton_3 = (Button) findViewById(R.id.answerbutton_3); answerButton_3.setHeight(heightMultiple); answerButton_3.setTextSize(buttonsTextFontSize ); ViewGroup.LayoutParams answerButton_3_params = answerButton_3 .getLayoutParams(); answerButton_3_params.width = widthMultiple; answerButton_3.setLayoutParams(answerButton_3_params); answerButton_3.setTypeface(typeface); answerButton_3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Log.e("Elango", "Button 3 clicked"); if (TamilLetters.getQuizOptions()[2].equals(TamilLetters .getUriMeiLetter())) { //Log.e("Elango", "Answer 3 Correct"); playSuccessSound(); refreshTamilQuizLetter(); } else { answerButton_3.setBackgroundColor(Color .parseColor("#ff0000")); } } }); // ============================================== answerButton_4 = (Button) findViewById(R.id.answerbutton_4); answerButton_4.setHeight(heightMultiple); answerButton_4.setTextSize(buttonsTextFontSize ); ViewGroup.LayoutParams answerButton_4_params = answerButton_4 .getLayoutParams(); answerButton_4_params.width = widthMultiple; answerButton_4.setLayoutParams(answerButton_4_params); answerButton_4.setTypeface(typeface); answerButton_4.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Log.e("Elango", "Button 4 clicked"); if (TamilLetters.getQuizOptions()[3].equals(TamilLetters .getUriMeiLetter())) { //Log.e("Elango", "Answer 4 Correct"); playSuccessSound(); refreshTamilQuizLetter(); } else { answerButton_4.setBackgroundColor(Color .parseColor("#ff0000")); } } }); // ============================================== } void initializeSettings() { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); con = this.getBaseContext(); this.screenHeight = metrics.heightPixels; this.screenWidth = metrics.widthPixels; heightMultiple = screenHeight / 7; widthMultiple = screenWidth / 2; //pointsTextFontSize = screenWidth / 15; pointsTextFontSize = screenWidth / 18; buttonsTextFontSize = screenWidth /15; //Log.e("Elango", "pointsTextFontSize " + pointsTextFontSize ); // Lets make Heighyt divisions by Nine res = getResources(); POINTS_TEXT = res.getString(R.string.points); /** * TIME_REMAINING = res.getString(R.string.time_remaining); * WANT_TO_CONTINUE = res.getString(R.string.WantToContinue); * CONTINUE_YES = res.getString(R.string.ContinueYES); CONTINUE_NO = * res.getString(R.string.ContinueNO); */ typeface = Typeface.createFromAsset(this.getAssets(), "fonts/TSCu_Paranar.ttf"); String[] tamilLettersArray = res .getStringArray(R.array.tamil_letters_array); String[] tamilLetterReferencesArray = res .getStringArray(R.array.tamil_letters_name_reference_array); TamilLetters.tamilLettersArray = tamilLettersArray; TamilLetters.tamilLetterReferencesArray = tamilLetterReferencesArray; } private void initTamilQuizLetter() { TamilLetters tamilLetter = TamilLetters.getTamilLetters(); tamilLetter.initializeAndRefresh(); randomNumUirMeiReference = tamilLetter.getActiveUirMeiReference(); } private void refreshTamilQuizLetter() { handler.postDelayed(new Runnable() { public void run() { // Do something after 5s = 5000ms gamePoints = gamePoints + 1; TamilLetters tamilLetter = TamilLetters.getTamilLetters(); tamilLetter.initializeAndRefresh(); randomNumUirMeiReference = tamilLetter.getActiveUirMeiReference(); initRefreshDisplayText(); } }, 4000); } void initRefreshDisplayText() { pointButton.setBackgroundColor(Color.parseColor("#32cd32")); pointButton.setText(ReEncodeTamil.unicode2tsc(POINTS_TEXT) + " " + gamePoints); questionButton.setText(ReEncodeTamil.unicode2tsc(TamilLetters .getUirPart()) + " + " + ReEncodeTamil.unicode2tsc(TamilLetters.getMeiPart()) + " = ? "); questionButton.setTextColor(Color.BLACK); answerButton_1.setBackgroundColor(Color.parseColor("#00ffff")); answerButton_1.setText(ReEncodeTamil.unicode2tsc(TamilLetters .getQuizOptions()[0])); //Log.e("Elango", "0= " + TamilLetters.getQuizOptions()[0] ); answerButton_2.setBackgroundColor(Color.parseColor("#dda0dd")); answerButton_2.setText(ReEncodeTamil.unicode2tsc(TamilLetters .getQuizOptions()[1])); //Log.e("Elango", "1= " + TamilLetters.getQuizOptions()[1] ); answerButton_3.setBackgroundColor(Color.parseColor("#a020f0")); answerButton_3.setText(ReEncodeTamil.unicode2tsc(TamilLetters .getQuizOptions()[2])); //Log.e("Elango", "2= " + TamilLetters.getQuizOptions()[2] ); answerButton_4.setBackgroundColor(Color.parseColor("#0000cd")); answerButton_4.setText(ReEncodeTamil.unicode2tsc(TamilLetters .getQuizOptions()[3])); //Log.e("Elango", "3= " + TamilLetters.getQuizOptions()[3] ); } protected void releaseMediaPlayers() { if (mediaPlay != null) { mediaPlay.stop(); mediaPlay.release(); mediaPlay = null; } } protected void onStop(){ super.onStop(); releaseMediaPlayers(); } private void playSuccessSound() { releaseMediaPlayers(); mediaPlay = MediaPlayer.create(this, R.raw.clap_short); mediaPlay.start(); //final String speaksuccess= "That is Correct . The letter is "+ spriteCharacter + " . Now find the next letter "; mediaPlay.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { releaseMediaPlayers(); mediaPlay = MediaPlayer.create(con,audio_files[randomNumUirMeiReference]); mediaPlay.start(); } }); } }
23.392687
116
0.668547
9a1cb93f90409921a55e9ff6f6904d6794a3bb32
15,200
package no.ks.eventstore2.eventstore; import akka.ConfigurationException; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.cluster.Cluster; import akka.cluster.ClusterEvent; import akka.cluster.singleton.ClusterSingletonManager; import akka.cluster.singleton.ClusterSingletonManagerSettings; import akka.cluster.singleton.ClusterSingletonProxy; import akka.cluster.singleton.ClusterSingletonProxySettings; import akka.dispatch.OnFailure; import akka.dispatch.OnSuccess; import com.google.common.collect.HashMultimap; import eventstore.Messages; import no.ks.eventstore2.Event; import no.ks.eventstore2.TakeBackup; import no.ks.eventstore2.TakeSnapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Future; import java.text.SimpleDateFormat; import java.util.HashSet; import static akka.dispatch.Futures.future; public class EventStore extends UntypedActor { public static final String EVENTSTOREMESSAGES = "eventstoremessages"; private static Logger log = LoggerFactory.getLogger(EventStore.class); private HashMultimap<String, ActorRef> aggregateSubscribers = HashMultimap.create(); JournalStorage storage; private ActorRef eventstoresingeltonProxy; private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); public static Props mkProps(JournalStorage journalStorage) { return Props.create(EventStore.class, journalStorage); } public EventStore(JournalStorage journalStorage) { storage = journalStorage; } @Override public void preStart() { try { Cluster cluster = Cluster.get(getContext().system()); cluster.subscribe(self(), ClusterEvent.MemberRemoved.class); log.info("{} subscribes to cluster events", self()); } catch (ConfigurationException e) { } final ActorSystem system = context().system(); try { Cluster cluster = Cluster.get(system); final ClusterSingletonManagerSettings settings = ClusterSingletonManagerSettings.create(system); system.actorOf(ClusterSingletonManager.props( EventstoreSingelton.mkProps(storage), "shutdown", settings), "eventstoresingelton"); ClusterSingletonProxySettings proxySettings = ClusterSingletonProxySettings.create(system); proxySettings.withBufferSize(10000); eventstoresingeltonProxy = system.actorOf(ClusterSingletonProxy.props("/user/eventstoresingelton", proxySettings), "eventstoresingeltonProxy"); } catch (ConfigurationException e) { log.info("not cluster system"); eventstoresingeltonProxy = system.actorOf(EventstoreSingelton.mkProps(storage)); } log.debug("Eventstore started with adress {}", getSelf().path()); } private void readAggregateEvents(RetrieveAggregateEventsAsync retreiveAggregateEvents) { final ActorRef sender = sender(); final ActorRef self = self(); final Future<EventBatch> future = storage.loadEventsForAggregateIdAsync(retreiveAggregateEvents.getAggregateType(), retreiveAggregateEvents.getAggregateId(), retreiveAggregateEvents.getFromJournalId()); future.onSuccess(new OnSuccess<EventBatch>() { @Override public void onSuccess(EventBatch result) throws Throwable { sender.tell(result, self); } }, getContext().dispatcher()); future.onFailure(new OnFailure() { @Override public void onFailure(Throwable failure) throws Throwable { log.error("failed to read events from journalstorage {} ", retreiveAggregateEvents, failure); } }, getContext().dispatcher() ); } private void readAggregateEvents(Messages.RetreiveAggregateEventsAsync retreiveAggregateEvents) { final ActorRef sender = sender(); final ActorRef self = self(); final Future<Messages.EventWrapperBatch> future = storage.loadEventWrappersForAggregateIdAsync(retreiveAggregateEvents.getAggregateType(), retreiveAggregateEvents.getAggregateRootId(), retreiveAggregateEvents.getFromJournalId()); future.onSuccess(new OnSuccess<Messages.EventWrapperBatch>() { @Override public void onSuccess(Messages.EventWrapperBatch result) throws Throwable { sender.tell(result, self); } }, getContext().dispatcher()); future.onFailure(new OnFailure() { @Override public void onFailure(Throwable failure) throws Throwable { log.error("failed to read events from journalstorage {} ", retreiveAggregateEvents, failure); } }, getContext().dispatcher() ); } private void readAggregateEvents(Messages.RetreiveCorrelationIdEventsAsync retreiveAggregateEvents) { final ActorRef sender = sender(); final ActorRef self = self(); final Future<Messages.EventWrapperBatch> future = storage.loadEventWrappersForCorrelationIdAsync(retreiveAggregateEvents.getAggregateType(), retreiveAggregateEvents.getCorrelationId(), retreiveAggregateEvents.getFromJournalId()); future.onSuccess(new OnSuccess<Messages.EventWrapperBatch>() { @Override public void onSuccess(Messages.EventWrapperBatch result) throws Throwable { sender.tell(result, self); } }, getContext().dispatcher()); future.onFailure(new OnFailure() { @Override public void onFailure(Throwable failure) throws Throwable { log.error("failed to read events from journalstorage {} ", retreiveAggregateEvents, failure); } }, getContext().dispatcher() ); } public void onReceive(Object o) throws Exception { log.debug("Received message {}", o); try { if (o instanceof String && "fail".equals(o)) { eventstoresingeltonProxy.tell(o, sender()); } if (o instanceof ClusterEvent.MemberRemoved) { ClusterEvent.MemberRemoved removed = (ClusterEvent.MemberRemoved) o; log.info("Member removed: {} status {}", removed.member(), removed.previousStatus()); for (String aggregate : aggregateSubscribers.keySet()) { HashSet<ActorRef> remove = new HashSet<ActorRef>(); for (ActorRef actorRef : aggregateSubscribers.get(aggregate)) { if (actorRef.path().address().equals(removed.member().address())) { remove.add(actorRef); log.debug("removeing actorref {}", actorRef); } } for (ActorRef actorRef : remove) { aggregateSubscribers.get(aggregate).remove(actorRef); log.info("Aggregate {} removeed subscriber {}", aggregate, actorRef); } } } else if (o instanceof Subscription) { Subscription subscription = (Subscription) o; tryToFillSubscription(sender(), subscription); } else if (o instanceof Messages.AsyncSubscription) { Messages.AsyncSubscription subscription = (Messages.AsyncSubscription) o; tryToFillSubscription(sender(), subscription); } else if (o instanceof RetrieveAggregateEventsAsync) { readAggregateEvents((RetrieveAggregateEventsAsync) o); } else if (o instanceof Messages.RetreiveAggregateEventsAsync) { readAggregateEvents((Messages.RetreiveAggregateEventsAsync) o); } else if (o instanceof Messages.RetreiveCorrelationIdEventsAsync) { readAggregateEvents((Messages.RetreiveCorrelationIdEventsAsync) o); } else if (o instanceof String || o instanceof Subscription || o instanceof Messages.Subscription || o instanceof Messages.LiveSubscription || o instanceof StoreEvents || o instanceof Event || o instanceof Messages.EventWrapper || o instanceof Messages.EventWrapperBatch || o instanceof AcknowledgePreviousEventsProcessed || o instanceof RetreiveAggregateEvents || o instanceof Messages.RetreiveAggregateEvents || o instanceof UpgradeAggregate || o instanceof TakeBackup || o instanceof RemoveSubscription || o instanceof Messages.RemoveSubscription || o instanceof TakeSnapshot || o instanceof Messages.GetSubscribers || o instanceof AcknowledgePreviousEventsProcessed || o instanceof Messages.AcknowledgePreviousEventsProcessed){ if(!(o instanceof AcknowledgePreviousEventsProcessed || o instanceof RetreiveAggregateEvents || o instanceof Messages.AcknowledgePreviousEventsProcessed || o instanceof Messages.RetreiveAggregateEvents || o instanceof Messages.EventWrapperBatch)) log.info("Sending to singelton message {} from {}", o, sender()); if(o instanceof Messages.EventWrapperBatch){ log.info("Sending to singelton eventbatch for aggregate {} with {} events", ((Messages.EventWrapperBatch) o).getAggregateType(), ((Messages.EventWrapperBatch) o).getEventsCount()); } eventstoresingeltonProxy.tell(o, sender()); } } catch (Exception e) { log.error("Eventstore got an error: ", e); throw e; } } private void tryToFillSubscription(final ActorRef sender, final Messages.AsyncSubscription subscription) { final ActorRef self = self(); Future<Boolean> f = future(() -> { log.info("Got async subscription on {} from {}, filling subscriptions", subscription, sender); boolean finished = loadEvents(sender, subscription); if (!finished) { log.info("Async IncompleteSubscriptionPleaseSendNew"); sender.tell(Messages.IncompleteSubscriptionPleaseSendNew.newBuilder().setAggregateType(subscription.getAggregateType()).build(), self); } else { log.info("Async CompleteAsyncSubscriptionPleaseSendSyncSubscription"); sender.tell(Messages.CompleteAsyncSubscriptionPleaseSendSyncSubscription.newBuilder().setAggregateType(subscription.getAggregateType()).build(), self); } return finished; }, getContext().system().dispatcher()); f.onFailure(new OnFailure() { public void onFailure(Throwable failure) { log.error("Error in AsyncSubscribe, restarting subscriber", failure); sender.tell(new NewEventstoreStarting(), self); } }, getContext().system().dispatcher()); } private void tryToFillSubscription(final ActorRef sender, final Subscription subscription) { final ActorRef self = self(); if (subscription instanceof AsyncSubscription) { Future<Boolean> f = future(() -> { log.info("Got async subscription on {} from {}, filling subscriptions", subscription, sender); boolean finished = loadEvents(sender, subscription); if (!finished) { log.info("Async IncompleteSubscriptionPleaseSendNew"); sender.tell(new IncompleteSubscriptionPleaseSendNew(subscription.getAggregateType()), self); } else { log.info("Async CompleteAsyncSubscriptionPleaseSendSyncSubscription"); sender.tell(new CompleteAsyncSubscriptionPleaseSendSyncSubscription(subscription.getAggregateType()), self); } return finished; }, getContext().system().dispatcher()); f.onFailure(new OnFailure() { public void onFailure(Throwable failure) { log.error("Error in AsyncSubscribe, restarting subscriber", failure); sender.tell(new NewEventstoreStarting(), self); } }, getContext().system().dispatcher()); } else { log.info("Sending subscription to singelton {} from {}", eventstoresingeltonProxy.path(), sender().path()); eventstoresingeltonProxy.tell(subscription, sender()); } } private boolean loadEvents(final ActorRef sender, Subscription subscription) { boolean finished = false; if (subscription.getFromJournalId() == null || "".equals(subscription.getFromJournalId().trim())) { finished = storage.loadEventsAndHandle(subscription.getAggregateType(), new HandleEvent() { @Override public void handleEvent(Event event) { sendEvent(event, sender); } }); } else { finished = storage.loadEventsAndHandle(subscription.getAggregateType(), new HandleEvent() { @Override public void handleEvent(Event event) { sendEvent(event, sender); } }, subscription.getFromJournalId()); } return finished; } private boolean loadEvents(final ActorRef sender, Messages.AsyncSubscription subscription) { return storage.loadEventsAndHandle(subscription.getAggregateType(), new HandleEventMetadata() { @Override public void handleEvent(Messages.EventWrapper event) { sendEvent(event, sender); } }, subscription.getFromJournalId()); } private void sendEvent(Messages.EventWrapper event, ActorRef subscriber) { log.debug("Publishing event {} to {}", event, subscriber); subscriber.tell(event, self()); } private void sendEvent(Event event, ActorRef subscriber) { Event upgadedEvent = upgradeEvent(event); log.debug("Publishing event {} to {}", upgadedEvent, subscriber); subscriber.tell(upgadedEvent, self()); } private Event upgradeEvent(Event event) { Event currentEvent = event; Event upgraded = currentEvent.upgrade(); while (upgraded != currentEvent) { currentEvent = upgraded; upgraded = currentEvent.upgrade(); } return upgraded; } }
47.648903
237
0.620855
418b82fdeaa21c582146312ad18b48de0e8c4551
8,747
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import static android.net.ConnectivityManager.TYPE_ETHERNET; import static android.net.ConnectivityManager.TYPE_WIFI; import static android.net.ConnectivityManager.TYPE_WIMAX; import static android.net.NetworkIdentity.scrubSubscriberId; import static android.telephony.TelephonyManager.NETWORK_CLASS_2_G; import static android.telephony.TelephonyManager.NETWORK_CLASS_3_G; import static android.telephony.TelephonyManager.NETWORK_CLASS_4_G; import static android.telephony.TelephonyManager.NETWORK_CLASS_UNKNOWN; import static android.telephony.TelephonyManager.getNetworkClass; import static com.android.internal.util.ArrayUtils.contains; import android.content.res.Resources; import android.os.Parcel; import android.os.Parcelable; import com.android.internal.util.Objects; /** * Template definition used to generically match {@link NetworkIdentity}, * usually when collecting statistics. * * @hide */ public class NetworkTemplate implements Parcelable { /** {@hide} */ public static final int MATCH_MOBILE_ALL = 1; /** {@hide} */ public static final int MATCH_MOBILE_3G_LOWER = 2; /** {@hide} */ public static final int MATCH_MOBILE_4G = 3; /** {@hide} */ public static final int MATCH_WIFI = 4; /** {@hide} */ public static final int MATCH_ETHERNET = 5; /** * Set of {@link NetworkInfo#getType()} that reflect data usage. */ private static final int[] DATA_USAGE_NETWORK_TYPES; static { DATA_USAGE_NETWORK_TYPES = Resources.getSystem().getIntArray( com.android.internal.R.array.config_data_usage_network_types); } /** * Template to combine all {@link ConnectivityManager#TYPE_MOBILE} style * networks together. Only uses statistics for requested IMSI. */ public static NetworkTemplate buildTemplateMobileAll(String subscriberId) { return new NetworkTemplate(MATCH_MOBILE_ALL, subscriberId); } /** * Template to combine all {@link ConnectivityManager#TYPE_MOBILE} style * networks together that roughly meet a "3G" definition, or lower. Only * uses statistics for requested IMSI. */ public static NetworkTemplate buildTemplateMobile3gLower(String subscriberId) { return new NetworkTemplate(MATCH_MOBILE_3G_LOWER, subscriberId); } /** * Template to combine all {@link ConnectivityManager#TYPE_MOBILE} style * networks together that meet a "4G" definition. Only uses statistics for * requested IMSI. */ public static NetworkTemplate buildTemplateMobile4g(String subscriberId) { return new NetworkTemplate(MATCH_MOBILE_4G, subscriberId); } /** * Template to combine all {@link ConnectivityManager#TYPE_WIFI} style * networks together. */ public static NetworkTemplate buildTemplateWifi() { return new NetworkTemplate(MATCH_WIFI, null); } /** * Template to combine all {@link ConnectivityManager#TYPE_ETHERNET} style * networks together. */ public static NetworkTemplate buildTemplateEthernet() { return new NetworkTemplate(MATCH_ETHERNET, null); } private final int mMatchRule; private final String mSubscriberId; /** {@hide} */ public NetworkTemplate(int matchRule, String subscriberId) { this.mMatchRule = matchRule; this.mSubscriberId = subscriberId; } private NetworkTemplate(Parcel in) { mMatchRule = in.readInt(); mSubscriberId = in.readString(); } /** {@inheritDoc} */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mMatchRule); dest.writeString(mSubscriberId); } /** {@inheritDoc} */ public int describeContents() { return 0; } @Override public String toString() { final String scrubSubscriberId = scrubSubscriberId(mSubscriberId); return "NetworkTemplate: matchRule=" + getMatchRuleName(mMatchRule) + ", subscriberId=" + scrubSubscriberId; } @Override public int hashCode() { return Objects.hashCode(mMatchRule, mSubscriberId); } @Override public boolean equals(Object obj) { if (obj instanceof NetworkTemplate) { final NetworkTemplate other = (NetworkTemplate) obj; return mMatchRule == other.mMatchRule && Objects.equal(mSubscriberId, other.mSubscriberId); } return false; } /** {@hide} */ public int getMatchRule() { return mMatchRule; } /** {@hide} */ public String getSubscriberId() { return mSubscriberId; } /** * Test if given {@link NetworkIdentity} matches this template. */ public boolean matches(NetworkIdentity ident) { switch (mMatchRule) { case MATCH_MOBILE_ALL: return matchesMobile(ident); case MATCH_MOBILE_3G_LOWER: return matchesMobile3gLower(ident); case MATCH_MOBILE_4G: return matchesMobile4g(ident); case MATCH_WIFI: return matchesWifi(ident); case MATCH_ETHERNET: return matchesEthernet(ident); default: throw new IllegalArgumentException("unknown network template"); } } /** * Check if mobile network with matching IMSI. */ private boolean matchesMobile(NetworkIdentity ident) { if (ident.mType == TYPE_WIMAX) { // TODO: consider matching against WiMAX subscriber identity return true; } else { return (contains(DATA_USAGE_NETWORK_TYPES, ident.mType) && Objects.equal(mSubscriberId, ident.mSubscriberId)); } } /** * Check if mobile network classified 3G or lower with matching IMSI. */ private boolean matchesMobile3gLower(NetworkIdentity ident) { if (ident.mType == TYPE_WIMAX) { return false; } else if (matchesMobile(ident)) { switch (getNetworkClass(ident.mSubType)) { case NETWORK_CLASS_UNKNOWN: case NETWORK_CLASS_2_G: case NETWORK_CLASS_3_G: return true; } } return false; } /** * Check if mobile network classified 4G with matching IMSI. */ private boolean matchesMobile4g(NetworkIdentity ident) { if (ident.mType == TYPE_WIMAX) { // TODO: consider matching against WiMAX subscriber identity return true; } else if (matchesMobile(ident)) { switch (getNetworkClass(ident.mSubType)) { case NETWORK_CLASS_4_G: return true; } } return false; } /** * Check if matches Wi-Fi network template. */ private boolean matchesWifi(NetworkIdentity ident) { if (ident.mType == TYPE_WIFI) { return true; } return false; } /** * Check if matches Ethernet network template. */ private boolean matchesEthernet(NetworkIdentity ident) { if (ident.mType == TYPE_ETHERNET) { return true; } return false; } private static String getMatchRuleName(int matchRule) { switch (matchRule) { case MATCH_MOBILE_3G_LOWER: return "MOBILE_3G_LOWER"; case MATCH_MOBILE_4G: return "MOBILE_4G"; case MATCH_MOBILE_ALL: return "MOBILE_ALL"; case MATCH_WIFI: return "WIFI"; case MATCH_ETHERNET: return "ETHERNET"; default: return "UNKNOWN"; } } public static final Creator<NetworkTemplate> CREATOR = new Creator<NetworkTemplate>() { public NetworkTemplate createFromParcel(Parcel in) { return new NetworkTemplate(in); } public NetworkTemplate[] newArray(int size) { return new NetworkTemplate[size]; } }; }
31.577617
95
0.640905
e0a89732497f773a2b1e0481b4b6b79f13a3dea0
1,501
// Copyright 2007 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.test; import java.io.File; public class TapestryTestConstants { /** * The current working directory (i.e., property "user.dir"). */ public static final String CURRENT_DIR_PATH = System.getProperty("user.dir"); /** * The Surefire plugin sets basedir but DOES NOT change the current working directory. When building across modules, * basedir changes for each module, but user.dir does not. This value should be used when referecing local files. * Outside of surefire, the "basedir" property will not be set, and the current working directory will be the * default. */ public static final String MODULE_BASE_DIR_PATH = System.getProperty("basedir", CURRENT_DIR_PATH); /** * {@link #MODULE_BASE_DIR_PATH} as a file. */ public static final File MODULE_BASE_DIR = new File(MODULE_BASE_DIR_PATH); }
39.5
120
0.727515
2c1024cfc23683f151d30209d0558821fba9d14a
1,182
/* * This file is generated by jOOQ. */ package de.warhog.fpvlaptracker.jooq.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.11" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Pilots implements Serializable { private static final long serialVersionUID = 1894067737; private final String name; private final Long chipid; public Pilots(Pilots value) { this.name = value.name; this.chipid = value.chipid; } public Pilots( String name, Long chipid ) { this.name = name; this.chipid = chipid; } public String getName() { return this.name; } public Long getChipid() { return this.chipid; } @Override public String toString() { StringBuilder sb = new StringBuilder("Pilots ("); sb.append(name); sb.append(", ").append(chipid); sb.append(")"); return sb.toString(); } }
19.064516
60
0.594755
24179f9fdb3c607af2587fdf22124ad482cb5e8d
83,867
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of the Air Force. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. // =============================================================================== package avtas.lmcp.lmcpgen; import java.io.File; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.Vector; public class CppMethods { public static String series_name(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { if (info.seriesName.length() > 8) { throw new Exception("Error: Series name must be 8 characters or less.\n"); } return ws + info.seriesName; } public static String series_name_caps(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { if (info.seriesName.length() > 8) { throw new Exception("Error: Series name must be 8 characters or less.\n"); } return ws + info.seriesName.toUpperCase(); } public static String series_id(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + info.seriesNameAsLong; } public static String series_version(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + info.version; } public static String series_dir(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + info.namespace; } public static String namespace(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return info.namespace.replaceAll("/", "::"); } public static String root_filepath(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + getRootFilepath(info); } private static String getRootFilepath(MDMInfo info) { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = 0; i < tmp.length; i++) { str += "../"; } return str; } // Returns the date that the package was made public static String creation_date(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + DateFormat.getDateInstance(DateFormat.FULL).format(new Date()); } public static String makefile_series_dirs(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(ws); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append("-I").append(i.namespace).append(" "); } return buf.toString(); } public static String all_descendants(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String ret = ""; List<String> descendants = new ArrayList<String>(); add_descendants(infos, st.name, st.seriesName, descendants); for(String child : descendants) { ret += ws + "descendants.push_back(\"" + child + "\");\n"; } return ret; } public static String all_descendants_include(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String ret = ""; List<String> descendants = new ArrayList<String>(); add_descendants(infos, st.name, st.seriesName, descendants); for(String child : descendants) { ret += ws + "#include \"" + child.replace('.','/') + ".h\"\n"; } return ret; } public static void add_descendants(MDMInfo[] infos, String typename, String seriesname, List<String> descendants) { for (MDMInfo in : infos) { for (int i = 0; i < in.structs.length; i++) { if (in.structs[i].extends_name.equals(typename) && in.structs[i].extends_series.equals(seriesname)) { String child = in.structs[i].namespace.replace('/', '.') + "." + in.structs[i].name; if(!descendants.contains(child)) { descendants.add(child); add_descendants(infos, in.structs[i].name, in.structs[i].seriesName, descendants); } } } } } /* public static String namespace_dir(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + info.namespace; } */ public static String using_series_namespace(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append(ws + "using namespace " + namespace(infos, i, outfile, st, en, ws) + ";\n"); } return buf.toString(); } public static String namespace_caps(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = 0; i < tmp.length; i++) { str += tmp[i].toUpperCase() + (i != (tmp.length - 1) ? "_" : ""); } return ws + str; } public static String open_namespace(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = 0; i < tmp.length; i++) { str += ws + "namespace " + tmp[i] + " {\n"; } return str; } public static String close_namespace(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = tmp.length-1; i >=0 ; i--) { str += ws + "} // end namespace " + tmp[i] + "\n"; } return str; } public static String datatype_name(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + st.name; } public static String longdatatype_name(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = 0; i < tmp.length; i++) { str += tmp[i]; } return ws + str + st.name; } public static String longdatatype_name_dots(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; String[] tmp = info.namespace.split("/"); for (int i = 0; i < tmp.length; i++) { str += tmp[i] + "."; } return ws + str + st.name; } public static String datatype_name_caps(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + st.name.toUpperCase(); } public static String enum_name(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + en.name; } public static String enum_name_caps(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + en.name.toUpperCase(); } public static String gen_enum_fields(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); int len = en.entries.size(); for (int i = 0; i < len; i++) { EnumInfo.EnumEntry entry = en.entries.get(i); buf.append(ws + "/** " + entry.comment + " */\n"); buf.append(ws + entry.name); buf.append(" = " + entry.value); if (i != len - 1) { buf.append(",\n"); } else { buf.append("\n"); } } return buf.toString(); } public static String gen_enum_for_string(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (EnumInfo.EnumEntry entry : en.entries) { buf.append(ws + "if ( str == \"" + entry.name + "\") return " + entry.name + ";\n"); } buf.append(ws + " return " + en.entries.get(0).name + ";\n"); return buf.toString(); } public static String gen_string_for_enum(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (EnumInfo.EnumEntry entry : en.entries) { buf.append(ws + "case " + entry.name + ": return \"" + entry.name + "\";\n"); } buf.append(ws + "default: return \"" + en.entries.get(0).name + "\";\n"); return buf.toString(); } public static String datatype_id(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + st.id; } public static String parent_datatype_filepath(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + (st.extends_name.length() == 0 ? "avtas/lmcp/Object" : getSeriesFilepath(infos, st.extends_series) + st.extends_name); } public static String full_parent_datatype(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return ws + (st.extends_name.length() == 0 ? "avtas::lmcp::Object" : getSeriesNamespace(infos, st.extends_series) + st.extends_name); } public static String include_dependencies(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String namespace = MDMReader.getMDM(st.fields[i].seriesName, infos).namespace; if (st.fields[i].isStruct && !st.fields[i].type.equals(MDMInfo.LMCP_OBJECT_NAME)) { str += ws + "#include \"" + namespace + "/" + st.fields[i].type + ".h\"\n"; } else if (st.fields[i].isEnum) { str += ws + "#include \"" + namespace + "/" + st.fields[i].type + ".h\"\n"; } } return str; } public static String include_sub_dependencies(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { Vector<StructInfo> subs = new Vector<StructInfo>(); for (int i = 0; i < st.fields.length; i++) { if (st.fields[i].isStruct) { subs.addAll(getAllCppSubclasses(infos, st.fields[i])); } } StringBuffer buf = new StringBuffer(); for (StructInfo i : subs) { buf.append("#include \"" + i.namespace + "/" + i.name + ".h\"\n"); } return buf.toString(); } public static String include_series_headers(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append(ws).append("#include " + i.namespace + "/" + i.seriesName.toLowerCase() + ".h\n"); } return buf.toString(); } public static String include_parent_type(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StructInfo parent = MDMInfo.getParentType(infos, st); if (parent != null) { return "#include \"" + parent.namespace + "/" + parent.name + ".h\"\n"; } return "#include \"avtas/lmcp/Object.h\"\n"; } public static String declare_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getResolvedTypeName(infos, st.fields[i]); // Add field comment str += ws + "/**" + st.fields[i].comment.replaceAll("\\s+", " ").replaceAll("<br", "\n" + ws + "*<br") + "*/\n"; // Scalar if (!st.fields[i].isArray) { str += ws + type + (st.fields[i].isStruct ? "* " : " ") + name + ";\n"; } // Arrays else { //variable length if (st.fields[i].length == -1) { if (st.fields[i].isStruct) { str += ws + "std::vector< " + type + "* > " + name + ";\n"; } else { str += ws + "std::vector< " + type + " > " + name + ";\n"; } } //fixed length else { if (st.fields[i].isStruct) { str += ws + type + "* " + name + "[" + st.fields[i].length + "];\n"; } else { str += ws + type + " " + name + "[" + st.fields[i].length + "];\n"; } } } } return str; } public static String copy_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; if (st.fields[i].isStruct && !st.fields[i].isArray) { str += ws + "newObj->" + name + " = " + name + "->clone();\n"; } else { str += ws + "newObj->" + name + " = " + name + ";\n"; } } return str; } public static String gets_and_sets_header(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String name2 = name.substring(2, 3).toUpperCase() + name.substring(3); String type = getResolvedTypeName(infos, st.fields[i]); // Add field comment str += ws + "/**" + st.fields[i].comment.replaceAll("\\s+", " ").replaceAll("<br", "\n" + ws + "*<br") + "(Units: " + st.fields[i].units + ")*/\n"; // Scalar if (!st.fields[i].isArray) { // get method str += ws + type + (st.fields[i].isStruct ? "* const" : "") + " get" + name2 + "(void) " + (st.fields[i].isStruct ? "" : "const ") + "{ return " + name + "; }\n"; // set method (declaration only) str += ws + st.name + "& set" + name2 + "(const " + type + (st.fields[i].isStruct ? "* const" : "") + " val);\n"; } // Arrays else { // get method only if (st.fields[i].length == -1) { if (st.fields[i].isStruct) { str += ws + "std::vector<" + type + "*> & get" + name2 + "(void) { return " + name + "; }\n"; } else { str += ws + "std::vector<" + type + "> & get" + name2 + "(void) { return " + name + "; }\n"; } } else { if (st.fields[i].isStruct) { str += ws + type + "** get" + name2 + "(void) { return " + name + "; }\n"; } else { str += ws + type + "* get" + name2 + "(void) { return " + name + "; }\n"; } } } str += "\n"; } return str; } public static String gets_and_sets_implementation(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String name2 = name.substring(2, 3).toUpperCase() + name.substring(3); String type = getResolvedTypeName(infos, st.fields[i]); // Scalar if (!st.fields[i].isArray) { // set method str += ws + st.name + "& " + st.name + "::set" + name2 + "(const " + type + (st.fields[i].isStruct ? "* const" : "") + " val)\n" + ws + "{\n"; if (st.fields[i].isStruct) { str += ws + " if (" + name + " != nullptr) { delete " + name + "; " + name + " = nullptr; }\n"; str += ws + " if (val != nullptr) { " + name + " = const_cast< " + type + "* > (val); }\n"; } else { str += ws + " " + name + " = val;\n"; } str += ws + " return *this;\n"; str += ws + "}\n"; } // Arrays else { // no implemented methods } str += "\n"; } return str; } public static String default_initializer_list(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String type = getResolvedTypeName(infos, st.fields[i]); String name = "__" + st.fields[i].name; String defaultVal = getCppDefaultVal(infos, st.fields[i]); // Scalar if (!st.fields[i].isArray) { str += ws + name + "(" + defaultVal + ");\n"; } // Arrays else { // fixed-length only if (st.fields[i].length != -1) { str += ws + name + "(" + type + "(" + st.fields[i].length + "));\n"; } } } return str; } public static String initialize_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getResolvedTypeName(infos, st.fields[i]); String defaultVal = getCppDefaultVal(infos, st.fields[i]); // Scalar if (!st.fields[i].isArray) { if (st.fields[i].isStruct) { if (st.fields[i].defaultVal.equalsIgnoreCase("null")) { str += ws + name + " = nullptr;\n"; } else { str += ws + name + " = new " + type + "();\n"; } } else { str += ws + name + " = " + defaultVal + ";\n"; } } // Arrays else { // Fixed-length if (st.fields[i].length != -1) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws + "{\n"; if (st.fields[i].isStruct) { if (st.fields[i].defaultVal.equalsIgnoreCase("null")) { str += ws + " " + name + "[i] = nullptr;\n"; } else { str += ws + " " + name + "[i] = new " + type + "();\n"; } } else { str += ws + " " + name + "[i] = " + defaultVal + ";\n"; } str += ws + "}\n"; } } } return str; } public static String copy_initializer_list(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String type = getResolvedTypeName(infos, st.fields[i]); String name = "__" + st.fields[i].name; // Scalar if (!st.fields[i].isArray) { if (st.fields[i].isStruct) { str += ws + name + " = that." + name + " == nullptr ? nullptr : that." + name + "->clone();\n"; } else { str += ws + name + " = that." + name + ";\n"; } } // Arrays else { if (st.fields[i].length != -1) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws + "{\n"; if (st.fields[i].isStruct) { str += ws + " " + name + "[i] = ( that." + name + " == nullptr ? nullptr : that." + name + "[i]->clone());\n"; } else { str += ws + " " + name + "[i] = that." + name + "[i];\n"; } str += ws + "}\n"; } else { str += ws + name + ".clear();\n"; str += ws + "for (size_t i=0; i< that." + name + ".size(); i++)\n" + ws + "{\n"; if (st.fields[i].isStruct) { str += ws + " " + name + ".push_back( that." + name + "[i] == nullptr ? nullptr : that." + name + "[i]->clone());\n"; } else { str += ws + " " + name + ".push_back( that." + name + "[i]);\n"; } str += ws + "}\n"; } //str += ",\n" + ws + name + "(that." + name + ")"; } } return str; } private static String cppObjectCompare(MDMInfo[] infos, FieldInfo field, String name, String ws) throws Exception { String str = ""; str += ws + "if(" + name + " && that." + name + ")\n" + ws + "{\n"; str += ws + " if(" + name + "->getSeriesNameAsLong() != that." + name + "->getSeriesNameAsLong()) return false;\n"; str += ws + " if(" + name + "->getSeriesVersion() != that." + name + "->getSeriesVersion()) return false;\n"; str += ws + " if(" + name + "->getLmcpType() != that." + name + "->getLmcpType()) return false;\n"; str += ws + " if( *(" + name + ") != *(that." + name + ") ) return false;\n"; str += ws + "}\n" + ws + "else if(" + name + " != that." + name + ") return false;\n"; return str; } public static String equals_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String type = getResolvedTypeName(infos, st.fields[i]); String name = "__" + st.fields[i].name; // Scalar if (!st.fields[i].isArray) { if (st.fields[i].isStruct) { str += cppObjectCompare(infos, st.fields[i], name, ws); } else { str += ws + "if(" + name + " != that." + name + ") return false;\n"; } } // Arrays else { if (st.fields[i].length != -1) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws + "{\n"; } else { str += ws + "if(" + name + ".size() != that." + name + ".size()) return false;\n"; str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; } if (st.fields[i].isStruct) { str += cppObjectCompare(infos, st.fields[i], name + "[i]", ws + " "); } else { str += ws + " if(" + name + "[i] != that." + name + "[i]) return false;\n"; } str += ws + "}\n"; } } str += ws + "return true;\n"; return str; } public static String assign_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String type = getResolvedTypeName(infos, st.fields[i]); String name = "__" + st.fields[i].name; String name2 = name.substring(2, 3).toUpperCase() + name.substring(3); // Scalar if (!st.fields[i].isArray) { str += ws + "set" + name2 + "(that." + name + ");\n"; } // Arrays else { str += ws + name + " = that." + name + ";\n"; } } return str; } public static String destroy_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; // Scalar if (st.fields[i].isScalar && st.fields[i].isStruct) { str += ws + "if (" + name + " != nullptr) delete " + name + ";\n"; } // Arrays else { if (st.fields[i].length == -1) { if (st.fields[i].isStruct) { str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; str += ws + " if (" + name + "[i] != nullptr) delete " + name + "[i];\n" + ws + "}\n"; } } else { if (st.fields[i].isStruct) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws + "{\n"; str += ws + " if ( " + name + "[i] != nullptr ) delete " + name + "[i];\n" + ws + "}\n"; } } } } return str; } public static String pack_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getCppTypeName(infos, st.fields[i]); String putName = "put" + getByteBufferTypeUpperCase(st.fields[i].type); // Scalar if (!st.fields[i].isArray) { // objects if (st.fields[i].isStruct) { if (!st.fields[i].isOptional) { str += ws + String.format("assert(%s != nullptr);\n", name); } str += ws + "avtas::lmcp::Factory::putObject( (avtas::lmcp::Object*) " + name + ", buf);\n"; } else if (st.fields[i].isEnum) { str += ws + "buf.putInt( (int32_t) " + name + ");\n"; } // primitives else { str += ws + "buf." + putName + "(" + name + ");\n"; } } // Arrays else { if (st.fields[i].length == -1) { if (st.fields[i].isLargeArray) { str += ws + "buf.putUInt( static_cast<uint32_t>(" + name + ".size()));\n"; } else { str += ws + "buf.putUShort( static_cast<uint16_t>(" + name + ".size()));\n"; } str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; } else { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws + "{\n"; } if (st.fields[i].isStruct) { str += ws + " assert(" + name + "[i] != nullptr);\n"; str += ws + " avtas::lmcp::Factory::putObject( (avtas::lmcp::Object*) " + name + "[i], buf);\n"; } else if (st.fields[i].isEnum) { str += ws + " buf.putInt( (int32_t) " + name + "[i]);\n"; } else { str += ws + " buf." + putName + "(" + name + "[i]);\n"; } str += ws + "}\n"; } } return str; } public static String unpack_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getResolvedTypeName(infos, st.fields[i]); String getFunc = "get" + getByteBufferTypeUpperCase(st.fields[i].type); // Scalar if (!st.fields[i].isArray) { // objects if (st.fields[i].isStruct) { str += ws + "{\n"; str += ws + " if (" + name + " != nullptr) delete " + name + ";\n"; str += ws + " " + name + " = nullptr;\n"; str += ws + " if (buf.getBool())\n" + ws + " {\n"; str += ws + " int64_t series_id = buf.getLong();\n"; str += ws + " uint32_t msgtype = buf.getUInt();\n"; str += ws + " uint16_t version = buf.getUShort();\n"; str += ws + " " + name + " = (" + type + "*) avtas::lmcp::Factory::createObject( series_id, msgtype, version );\n"; str += ws + " if (" + name + " != nullptr) " + name + "->unpack(buf);\n"; if (!st.fields[i].isOptional) { str += ws + " else assert(" + name + " != nullptr);\n"; } str += ws + " }\n"; str += ws + "}\n"; } else if (st.fields[i].isEnum) { str += ws + name + " = (" + type + ") buf.getInt();\n"; } // primitives else { str += ws + name + " = buf." + getFunc + "();\n"; } } // Arrays else { if (st.fields[i].length == -1) { if (st.fields[i].isStruct) { str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; str += ws + " if (" + name + "[i] != nullptr)\n"; str += ws + " delete " + name + "[i];\n"; str += ws + "}\n"; } str += ws + name + ".clear();\n"; if (st.fields[i].isLargeArray) { str += ws + "uint32_t " + name + "_length = buf.getUInt();\n"; } else { str += ws + "uint16_t " + name + "_length = buf.getUShort();\n"; } str += ws + "for (uint32_t i=0; i< " + name + "_length; i++)\n" + ws + "{\n"; } else { if (st.fields[i].isStruct) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws +"{\n"; str += ws + " if (" + name + "[i] != nullptr)\n"; str += ws + " delete " + name + "[i];\n"; str += ws + " " + name + "[i] = nullptr;\n"; str += ws + "}\n"; } str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws +"{\n"; } if (st.fields[i].isStruct) { str += ws + " if (buf.getBool())\n" + ws + " {\n"; str += ws + " int64_t series_id = buf.getLong();\n"; str += ws + " uint32_t msgtype = buf.getUInt();\n"; str += ws + " uint16_t version = buf.getUShort();\n"; str += ws + " " + type + "* e = (" + type + "*) avtas::lmcp::Factory::createObject( series_id, msgtype, version );\n"; str += ws + " if ( e != nullptr) e->unpack(buf); \n"; str += ws + " else assert( e != nullptr); \n"; if (st.fields[i].length == -1) { str += ws + " " + name + ".push_back(e);\n"; } else { str += ws + " " + name + "[i] = e;\n"; } str += ws + " }\n"; } else if (st.fields[i].isEnum) { if (st.fields[i].length == -1) { str += ws + " " + name + ".push_back( (" + type + ") buf.getInt() );\n"; } else { str += ws + " " + name + "[i] = (" + type + ") buf.getInt();\n"; } } else { if (st.fields[i].length == -1) { str += ws + " " + name + ".push_back(buf." + getFunc + "() );\n"; } else { str += ws + " " + name + "[i] = buf." + getFunc + "();\n"; } } str += ws + "}\n"; } } return str; } public static String tostring_attributes(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; if (st.extends_name.length() > 0) { str += tostring_attributes(infos, info, outfile, MDMInfo.getParentType(infos, st), en, ws) + "\n"; } for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getCppTypeName(infos, st.fields[i]); // Scalar if (!st.fields[i].isArray) { // objects if (st.fields[i].isStruct) { str += ws + "oss << indent << \"" + st.fields[i].name + " (" + type + ")\";\n"; str += ws + "if (" + name + " == nullptr)\n"; str += ws + " oss << \" = nullptr\";\n"; str += ws + "oss << \"\\n\";\n"; } // primitives else { str += ws + "oss << indent << \"" + st.fields[i].name + " (" + type + ") = \" << "; if (type.equalsIgnoreCase("string")) { str += "\"\\\"\" << " + name + "<< \"\\\"\""; } else if (type.equalsIgnoreCase("char")) { str += "\"\\\'\" << " + name + "<< \"\\\'\""; } else if (type.equalsIgnoreCase("byte")) { str += "(int32_t)" + name; } else { str += name; } str += " << \"\\n\";\n"; } } // Arrays else { if (st.fields[i].length == -1) { str += ws + "oss << indent << \"" + st.fields[i].name + " (" + st.fields[i].type + " [ \" << " + name + ".size() << \", var ])\\n\";\n"; } else { str += ws + "oss << indent << \"" + st.fields[i].name + " (" + st.fields[i].type + " [ \" << " + name + " << \" ])\\n\";\n"; } } } return str; } public static String calculate_packed_size(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { String name = "__" + st.fields[i].name; String type = getResolvedTypeName(infos, st.fields[i]); // Scalar if (!st.fields[i].isArray) { // objects if (st.fields[i].isStruct) { // 15 = boolean (1 byte), series name (8 bytes), type (4 bytes) , version number (2 bytes) str += ws + "size += (" + name + " != nullptr ? " + name + "->calculatePackedSize() + 15 : 1);\n"; } // primitives else { if (st.fields[i].type.equalsIgnoreCase("string")) { str += ws + "size += 2 + " + name + ".length();\n"; } else { str += ws + "size += sizeof(" + type + ");\n"; } } } // Arrays else { if (st.fields[i].length == -1) { if (st.fields[i].isStruct) { if (st.fields[i].isLargeArray) { str += ws + "size += 4;\n"; // space for uint to indicate length } else { str += ws + "size += 2;\n"; // space for ushort to indicate length } str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; str += ws + " if (" + name + "[i] != nullptr)\n" + ws + " {\n"; // 15 = boolean (1 byte), series name (8 bytes), type (4 bytes) , version number (2 bytes) str += ws + " size += " + name + "[i]->calculatePackedSize() + 15;\n"; str += ws + " }\n"; str += ws + " else { size += 1; }\n"; str += ws + "}\n"; } else if (st.fields[i].type.equals("string")) { if (st.fields[i].isLargeArray) { str += ws + "size += 4;\n"; // space for uint to indicate length } else { str += ws + "size += 2;\n"; // space for ushort to indicate length } str += ws + "for (size_t i=0; i<" + name + ".size(); i++)\n" + ws + "{\n"; // get the length of the string + 2 bytes (placeholder for length) str += ws + " size += " + name + "[i].length() + 2;\n"; str += ws + "}\n"; } else { if (st.fields[i].isLargeArray) { str += ws + "size += 4 + sizeof(" + type + ") * " + name + ".size();\n"; } else { str += ws + "size += 2 + sizeof(" + type + ") * " + name + ".size();\n"; } } } else { //str += ws + "size += 2;\n"; // space for ushort to indicate length if (st.fields[i].isStruct) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws +"{\n"; str += ws + " if (" + name + "[i] != nullptr){\n;"; // 15 = boolean (1 byte), series name (8 bytes), type (4 bytes) , version number (2 bytes) str += ws + " size += " + name + "[i]->calculatePackedSize() + 15;\n"; str += ws + " }\n" + ws + " else { size += 1; }\n"; str += ws + "}\n"; } else if (st.fields[i].type.equals("string")) { str += ws + "for (uint32_t i=0; i<" + st.fields[i].length + "; i++)\n" + ws +"{\n"; // get the length of the string + 2 bytes (placeholder for length) str += ws + " size += " + name + "[i].length() + 2;\n"; str += ws + "}\n"; } else { str += ws + "size += sizeof(" + type + ") * " + st.fields[i].length + ";\n"; } } } } return str; } public static String include_all_types(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } for (StructInfo s : i.structs) { buf.append(ws + "#include \"" + i.namespace + "/" + s.name + ".h\"\n"); } buf.append(ws + "#include \"" + i.namespace + "/" + i.seriesName + "Enum.h\"\n"); } return buf.toString(); } public static String global_factory_switch(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append(ws + "if (series_id == " + i.seriesNameAsLong + "LL)\n"); buf.append(ws + " return " + namespace(infos, i, outfile, st, en, ws) + "::" + i.seriesName + "Factory::createObject(series_id, type, version);\n"); } return buf.toString(); } public static String series_factory_switch(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); buf.append(ws + "if (series_id == " + info.seriesNameAsLong + "LL)\n"); buf.append(ws + " if (version == " + info.version + ")\n"); buf.append(ws + " switch(type)\n" + ws + " {\n"); for (int j = 0; j < info.structs.length; j++) { buf.append(ws + " case " + info.structs[j].id + ": return new " + namespace(infos, info, outfile, st, en, ws) + "::" + info.structs[j].name + "; \n"); } buf.append(ws + " }\n"); return buf.toString(); } public static String series_enumeration(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < info.structs.length; i++) { str += ws + info.structs[i].name.toUpperCase() + " = " + info.structs[i].id + ",\n"; } return str.replaceAll(",\n$", ""); } public static String include_array_dependencies(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < st.fields.length; i++) { if (st.fields[i].isArray && st.fields[i].length == -1) { str += ws + "#include <vector>\n"; return str; } } return str; } public static String makefile_source_list(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } for (StructInfo si : i.structs) { String cleanNamespace = i.namespace.replaceAll("/",""); buf.append("\t" + i.namespace + "/" + cleanNamespace + si.name + ".cpp\\\n"); } buf.append("\t" + i.namespace + "/" + i.seriesName + "XMLReader.cpp\\\n"); buf.append("\t" + i.namespace + "/" + i.seriesName + "Factory.cpp\\\n"); } return buf.toString(); } public static String cmake_source_list(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } for (StructInfo si : i.structs) { String cleanNamespace = i.namespace.replaceAll("/",""); buf.append(ws + i.namespace + "/" + cleanNamespace + si.name + ".cpp\n"); } buf.append(ws + i.namespace + "/" + i.seriesName + "XMLReader.cpp\n"); buf.append(ws + i.namespace + "/" + i.seriesName + "Factory.cpp\n"); } return buf.toString(); } public static String meson_source_list(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } for (StructInfo si : i.structs) { String cleanNamespace = i.namespace.replaceAll("/",""); buf.append(ws + "'" + i.namespace + "/" + cleanNamespace + si.name + ".cpp',\n"); } buf.append(ws + "'" + i.namespace + "/" + i.seriesName + "XMLReader.cpp',\n"); buf.append(ws + "'" + i.namespace + "/" + i.seriesName + "Factory.cpp',\n"); } return buf.toString(); } public static String include_all_series_headers(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < info.structs.length; i++) { str += ws + "#include \"" + info.namespace + "/" + info.structs[i].name + ".h\"\n"; } for (int i = 0; i < info.enums.length; i++) { str += ws + "#include \"" + info.namespace + "/" + info.enums[i].name + ".h\"\n"; } str += ws + "#include \"" + info.namespace + "/" + info.seriesName + "Enum.h\"\n"; return str; } public static String include_entire_series(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < info.structs.length; i++) { str += ws + "#include \"" + info.namespace + "/" + info.structs[i].name + ".h\"\n"; } for (int i = 0; i < info.enums.length; i++) { str += ws + "#include \"" + info.namespace + "/" + info.enums[i].name + ".h\"\n"; } str += ws + "#include \"" + info.namespace + "/" + info.seriesName + "Enum.h\"\n"; return str; } public static String include_every_series(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } str += ws + "#include \"" + i.namespace + "/" + i.seriesName + ".h\"\n"; } return str; } public static String create_test_objects(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < info.structs.length; i++) { String type = namespace(infos, info, outfile, st, en, ws) + "::" + info.structs[i].name; String name = "obj" + info.structs[i].name.substring(0, 1).toUpperCase() + info.structs[i].name.substring(1); str += ws + type + "* " + name + " = new " + type + ";\n"; str += ws + "objects.push_back(" + name + ");\n"; } return str; } public static String xml_visit_series(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String seriesReader = getCppNamespace(i.namespace) + "::" + i.seriesName + "XMLReader"; buf.append(ws + "if (node->getAttribute(\"Series\") == \"" + i.seriesName + "\") return " + seriesReader + "::visitType(node);\n"); } return buf.toString(); } public static String xml_include_readers(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append(ws + "#include \"" + i.namespace + "/" + i.seriesName + "XMLReader.h\"\n"); } return buf.toString(); } public static String include_all_factories(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { StringBuffer buf = new StringBuffer(); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } buf.append(ws + "#include \"" + i.namespace + "/" + i.seriesName + "Factory.h\"\n"); } return buf.toString(); } public static String xml_create_visits(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; for (int i = 0; i < info.structs.length; i++) { StructInfo dt_tmp = info.structs[i]; str += ws + "if (type == \"" + dt_tmp.name + "\"){\n"; str += ws + " " + dt_tmp.name + "* o = new " + dt_tmp.name + "();\n"; str += ws + " for (uint32_t i=0; i<el->getChildCount(); i++)\n" + ws + " {\n"; str += ws + " std::string name = el->getChild(i)->getTagName();\n"; ArrayList<FieldInfo> fields = new ArrayList<FieldInfo>(); fields.addAll(Arrays.asList(dt_tmp.fields)); while (dt_tmp.extends_name.length() != 0) { dt_tmp = MDMInfo.getParentType(infos, dt_tmp); fields.addAll(Arrays.asList(dt_tmp.fields)); } for (int j = 0; j < fields.size(); j++) { FieldInfo f = fields.get(j); String setname = f.name.substring(0, 1).toUpperCase() + f.name.substring(1); String ctype = getResolvedTypeName(infos, f); str += ws + " if(name == \"" + f.name + "\")\n" + ws + " {\n"; str += ws + " Node* tmp = el->getChild(i);\n"; if (f.isArray) { str += ws + " for (uint32_t j=0; j<tmp->getChildCount(); j++)\n" + ws + " {\n"; if (f.length == -1) { if (f.isStruct) { str += ws + " Object* oo = readXML( tmp->getChild(j));\n"; str += ws + " o->get" + setname + "().push_back( (" + ctype + "*) oo);\n"; //str += ws + " delete oo;\n"; } else if (f.isEnum) { String enumspace = getSeriesNamespace(infos, f.seriesName) + f.type; str += ws + " o->get" + setname + "().push_back( " + enumspace + "::get_" + f.type + "(get_string( tmp->getChild(j))));\n"; } else { str += ws + " o->get" + setname + "().push_back( get_" + f.type + "( tmp->getChild(j)));\n"; } } else { if (f.isStruct) { str += ws + " Object* oo = readXML( tmp->getChild(j));\n"; str += ws + " o->get" + setname + "()[j] = (" + ctype + "*) oo;\n"; //str += ws + " delete oo;\n"; } else if (f.isEnum) { String enumspace = getSeriesNamespace(infos, f.seriesName) + f.type; str += ws + " o->get" + setname + "()[j] = " + enumspace + "::get_" + f.type + "( get_string( tmp->getChild(j)));\n"; } else { str += ws + " o->get" + setname + "()[j] = get_" + f.type + "( tmp->getChild(j));\n"; } } str += ws + " }\n"; } else { if (f.isStruct) { str += ws + " Object* oo = readXML( tmp->getChild(0) );\n"; str += ws + " if (oo) o->set" + setname + "((" + ctype + "*) oo );\n"; //str += ws + " delete oo;\n"; } else if (f.isEnum) { String enumspace = getSeriesNamespace(infos, f.seriesName) + f.type; str += ws + " o->set" + setname + "( " + enumspace + "::get_" + f.type + "( get_string( tmp )));\n"; } else { str += ws + " o->set" + setname + "( get_" + f.type + "( tmp ));\n"; } } str += ws + " continue;\n"; str += ws + " }\n"; } str += ws + " }\n"; str += ws + " return o;\n"; str += ws + "}\n"; } return str; } public static String xml_write_object(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; StructInfo dt_tmp = st; ArrayList<FieldInfo> fields = new ArrayList<FieldInfo>(); fields.addAll(Arrays.asList(dt_tmp.fields)); while (dt_tmp.extends_name.length() != 0) { dt_tmp = MDMInfo.getParentType(infos, dt_tmp); fields.addAll(Arrays.asList(dt_tmp.fields)); } str += ws + "str << ws << \"<" + st.name + " Series=\\\"" + st.seriesName + "\\\">\\n\";\n"; for (FieldInfo f : fields) { String varname = "__" + f.name; String cast = ""; if (f.type.equals("byte")) { cast = "(int32_t) "; } if (f.isArray) { str += ws + "str << ws << \" <" + f.name + ">\\n\";\n"; if (f.length == -1) { str += ws + "for (size_t i=0; i<" + varname + ".size(); i++)\n" + ws + "{\n"; } else { str += ws + "for (uint32_t i=0; i<" + f.length + "; i++)\n" + ws +"{\n"; } if (f.isStruct) { str += ws + " str << (" + varname + "[i] == nullptr ? ( ws + \" <null/>\\n\") : (" + varname + "[i]->toXML(depth + 1))) ;\n"; } else if (f.isEnum) { String fulltype = getCppNamespace(getSeriesNamespace(infos, f.seriesName)) + f.type; str += ws + " str << ws << \" <" + f.type + ">\" << " + fulltype + "::get_string(" + varname + "[i]) << \"</" + f.type + ">\\n\";\n"; } else { if (f.type.equals("bool")) { str += ws + " str << ws << \" <" + f.type + ">\" << (" + varname + "[i] ? \"true\" : \"false\") << \"</" + f.type + ">\\n\";\n"; } else { str += ws + " str << ws << \" <" + f.type + ">\" << " + cast + varname + "[i] << \"</" + f.type + ">\\n\";\n"; } } str += ws + "}\n"; str += ws + "str << ws << \" </" + f.name + ">\\n\";\n"; } else if (f.isStruct) { str += ws + "if (" + varname + " != nullptr)\n" + ws + "{\n"; str += ws + " str << ws << \" <" + f.name + ">\";\n"; str += ws + " str << \"\\n\" + " + varname + "->toXML(depth + 1) + ws + \" \";\n"; str += ws + " str << \"</" + f.name + ">\\n\";\n"; str += ws + "}\n"; } else if (f.isEnum) { String fulltype = getCppNamespace(getSeriesNamespace(infos, f.seriesName)) + f.type; str += ws + "str << ws << \" <" + f.name + ">\" << " + fulltype + "::get_string(" + varname + ") << \"</" + f.name + ">\\n\";\n"; } else { if (f.type.equals("bool")) { str += ws + "str << ws << \" <" + f.name + ">\" << (" + varname + " ? \"true\" : \"false\") << \"</" + f.name + ">\\n\";\n"; } else { str += ws + "str << ws << \" <" + f.name + ">\" << " + cast + varname + " << \"</" + f.name + ">\\n\";\n"; } } } str += ws + "str << ws << \"</" + st.name + ">\\n\";\n"; return str; } public static String send_all_messages(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ws + "// send out all of messages\n"; str += ws + "avtas::lmcp::ByteBuffer* sendBuf = nullptr;\n"; str += ws + "uint8_t* pBuf = nullptr;\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } for (StructInfo s : i.structs) { String ns = s.namespace.replaceAll("/", "::") + "::" + s.name; String cn = s.namespace.replaceAll("/", "") + s.name; str += "\n"; str += ws + ns + "* _" + cn.toLowerCase() + " = new " + ns + "();\n"; str += ws + "std::cout << \"Sending " + ns + "\" << std::endl;\n"; str += ws + "sendBuf = avtas::lmcp::Factory::packMessage(_" + cn.toLowerCase() + ", true);\n"; str += ws + "delete _" + cn.toLowerCase() + ";\n"; str += ws + "std::cout << sendBuf->toString() << std::endl;\n"; str += ws + "pBuf = sendBuf->array();\n"; str += ws + "send(connectionSocket, (char*) pBuf, sendBuf->position(), 0);\n"; str += ws + "delete sendBuf;\n"; } } return str; } public static String project_header_files(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { // lmcp specific headers String str = ws + "<Filter Name=\"lmcp\">\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\ByteBuffer.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\Factory.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\LmcpXMLReader.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\Node.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\NodeUtil.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\Object.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\XMLParser.h\"> </File>\n"; str += ws + "</Filter>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String winDir = i.namespace.replaceAll("/", "\\\\"); str += ws + "<Filter Name=\"" + winDir + "\">\n"; for (StructInfo s : i.structs) { str += ws + " <File RelativePath=\".\\" + winDir + "\\" + s.name + ".h\"> </File>\n"; } for (EnumInfo e : i.enums) { str += ws + " <File RelativePath=\".\\" + winDir + "\\" + e.name + ".h\"> </File>\n"; } str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + "XMLReader.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + "Factory.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + "Enum.h\"> </File>\n"; str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + ".h\"> </File>\n"; str += ws + "</Filter>\n"; } return str; } public static String project_source_files(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ws + "<Filter Name=\"lmcp\">\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\ByteBuffer.cpp\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\Factory.cpp\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\Node.cpp\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\NodeUtil.cpp\"> </File>\n"; str += ws + " <File RelativePath=\".\\avtas\\lmcp\\XMLParser.cpp\"> </File>\n"; str += ws + "</Filter>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String winDir = i.namespace.replaceAll("/", "\\\\"); String cleanNamespace = i.namespace.replaceAll("/",""); str += ws + "<Filter Name=\"" + winDir + "\">\n"; for (StructInfo s : i.structs) { str += ws + " <File RelativePath=\".\\" + winDir + "\\" + cleanNamespace + s.name + ".cpp\"> </File>\n"; } str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + "XMLReader.cpp\"> </File>\n"; str += ws + " <File RelativePath=\".\\" + winDir + "\\" + i.seriesName + "Factory.cpp\"> </File>\n"; str += ws + "</Filter>\n"; } return str; } public static String xproject_header_files(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { // lmcp specific headers String str = ws + ""; str += ws + " <ClInclude Include=\"avtas\\lmcp\\ByteBuffer.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Factory.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\LmcpXMLReader.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Node.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\NodeUtil.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Object.h\"/>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\XMLParser.h\"/>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String winDir = i.namespace.replaceAll("/", "\\\\"); for (StructInfo s : i.structs) { str += ws + " <ClInclude Include=\"" + winDir + "\\" + s.name + ".h\"/>\n"; } for (EnumInfo e : i.enums) { str += ws + " <ClInclude Include=\"" + winDir + "\\" + e.name + ".h\"/>\n"; } str += ws + " <ClInclude Include=\"" + winDir + "\\" + i.seriesName + "XMLReader.h\"/>\n"; str += ws + " <ClInclude Include=\"" + winDir + "\\" + i.seriesName + "Factory.h\"/>\n"; str += ws + " <ClInclude Include=\"" + winDir + "\\" + i.seriesName + "Enum.h\"/>\n"; str += ws + " <ClInclude Include=\"" + winDir + "\\" + i.seriesName + ".h\"/>\n"; } return str; } public static String xproject_source_files(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; str += ws + " <ClCompile Include=\"avtas\\lmcp\\ByteBuffer.cpp\"/>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\Factory.cpp\"/>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\Node.cpp\"/>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\NodeUtil.cpp\"/>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\XMLParser.cpp\"/>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String winDir = i.namespace.replaceAll("/", "\\\\"); String cleanNamespace = i.namespace.replaceAll("/",""); for (StructInfo s : i.structs) { str += ws + " <ClCompile Include=\"" + winDir + "\\" + cleanNamespace + s.name + ".cpp\"/>\n"; } str += ws + " <ClCompile Include=\"" + winDir + "\\" + i.seriesName + "XMLReader.cpp\"/>\n"; str += ws + " <ClCompile Include=\"" + winDir + "\\" + i.seriesName + "Factory.cpp\"/>\n"; } return str; } public static String xproject_setup_filters(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; List<String> namespaces = new ArrayList<String>(); namespaces.add("lmcp"); for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } namespaces.add(i.namespace.replaceAll("/", "%255c")); } for (String namespace : namespaces) { str += ws + "<Filter Include=\"Header Files\\" + namespace + "\">\n"; str += ws + " <UniqueIdentifier>{" + makeGUID() + "}</UniqueIdentifier>\n"; str += ws + "</Filter>\n"; str += ws + "<Filter Include=\"Source Files\\" + namespace + "\">\n"; str += ws + " <UniqueIdentifier>{" + makeGUID() + "}</UniqueIdentifier>\n"; str += ws + "</Filter>\n"; } return str; } public static String xproject_header_filters(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; str += ws + " <ClInclude Include=\"avtas\\lmcp\\ByteBuffer.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Factory.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\LmcpXMLReader.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Node.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\NodeUtil.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\Object.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"avtas\\lmcp\\XMLParser.h\">\n"; str += ws + " <Filter>Header Files\\lmcp</Filter>\n</ClInclude>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String filter = "Header Files\\" + i.namespace.replaceAll("/", "%255c"); String folder = i.namespace.replaceAll("/", "\\\\"); for (StructInfo s : i.structs) { str += ws + " <ClInclude Include=\"" + folder + "\\" + s.name + ".h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; } for (EnumInfo e : i.enums) { str += ws + " <ClInclude Include=\"" + folder + "\\" + e.name + ".h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; } str += ws + " <ClInclude Include=\"" + folder + "\\" + i.seriesName + "XMLReader.h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"" + folder + "\\" + i.seriesName + "Factory.h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"" + folder + "\\" + i.seriesName + "Enum.h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; str += ws + " <ClInclude Include=\"" + folder + "\\" + i.seriesName + ".h\">\n <Filter>" + filter + "</Filter>\n</ClInclude>\n"; } return str; } public static String xproject_source_filters(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ""; str += ws + " <ClCompile Include=\"avtas\\lmcp\\ByteBuffer.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\Factory.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\LmcpXMLReader.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\Node.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\NodeUtil.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\Object.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"avtas\\lmcp\\XMLParser.cpp\">\n"; str += ws + " <Filter>Source Files\\lmcp</Filter>\n</ClCompile>\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String filter = "Source Files\\" + i.namespace.replaceAll("/", "%255c"); String folder = i.namespace.replaceAll("/", "\\\\"); String cleanNamespace = i.namespace.replaceAll("/",""); for (StructInfo s : i.structs) { str += ws + " <ClCompile Include=\"" + folder + "\\" + cleanNamespace + s.name + ".cpp\">\n <Filter>" + filter + "</Filter>\n</ClCompile>\n"; } str += ws + " <ClCompile Include=\"" + folder + "\\" + i.seriesName + "XMLReader.cpp\">\n <Filter>" + filter + "</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"" + folder + "\\" + i.seriesName + "Factory.cpp\">\n <Filter>" + filter + "</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"" + folder + "\\" + i.seriesName + "Enum.cpp\">\n <Filter>" + filter + "</Filter>\n</ClCompile>\n"; str += ws + " <ClCompile Include=\"" + folder + "\\" + i.seriesName + ".cpp\">\n <Filter>" + filter + "</Filter>\n</ClCompile>\n"; } return str; } public static String pro_source_files(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { String str = ws + ".\\avtas\\lmcp\\ByteBuffer.cpp\\\n"; str += ws + "\t.\\avtas\\lmcp\\Factory.cpp\\\n"; str += ws + "\t.\\avtas\\lmcp\\Node.cpp\\\n"; str += ws + "\t.\\avtas\\lmcp\\NodeUtil.cpp\\\n"; str += ws + "\t.\\avtas\\lmcp\\XMLParser.cpp\\\n"; for (MDMInfo i : infos) { if(i.seriesNameAsLong == 0) { continue; } String winDir = i.namespace.replaceAll("/", "\\\\"); String cleanNamespace = i.namespace.replaceAll("/",""); for (StructInfo s : i.structs) { str += ws + "\t.\\" + winDir + "\\" + cleanNamespace + s.name + ".cpp\\\n"; } str += ws + "\t.\\" + winDir + "\\" + i.seriesName + "XMLReader.cpp\\\n"; str += ws + "\t.\\" + winDir + "\\" + i.seriesName + "Factory.cpp\\\n"; } return str.substring(0, str.length() - 2); } public static String vcproj_make_guid(MDMInfo[] infos, MDMInfo info, File outfile, StructInfo st, EnumInfo en, String ws) throws Exception { return makeGUID(); } ////////////////// Utility Functions //////////////////////////// private static String getCppTypeName(MDMInfo[] infos, FieldInfo field) { String type = field.type; if (type.equalsIgnoreCase("byte")) { return "uint8_t"; } if (type.equalsIgnoreCase("char")) { return "char"; } if (type.equalsIgnoreCase("bool")) { return "bool"; } if (type.equalsIgnoreCase("int16")) { return "int16_t"; } if (type.equalsIgnoreCase("uint16")) { return "uint16_t"; } if (type.equalsIgnoreCase("int32")) { return "int32_t"; } if (type.equalsIgnoreCase("uint32")) { return "uint32_t"; } if (type.equalsIgnoreCase("int64")) { return "int64_t"; } if (type.equalsIgnoreCase("real32")) { return "float"; } if (type.equalsIgnoreCase("real64")) { return "double"; } if (type.equalsIgnoreCase("string")) { return "std::string"; } if (type.equals(MDMInfo.LMCP_OBJECT_NAME)) { return "avtas::lmcp::Object"; } else if (field.isStruct) { getResolvedTypeName(infos, field); } return type; } private static String getCppTypeSize(String type) { if (type.equalsIgnoreCase("byte")) { return "1"; } if (type.equalsIgnoreCase("char")) { return "1"; } if (type.equalsIgnoreCase("bool")) { return "1"; } if (type.equalsIgnoreCase("int16")) { return "2"; } if (type.equalsIgnoreCase("uint16")) { return "2"; } if (type.equalsIgnoreCase("int32")) { return "4"; } if (type.equalsIgnoreCase("uint32")) { return "4"; } if (type.equalsIgnoreCase("int64")) { return "8"; } if (type.equalsIgnoreCase("real32")) { return "4"; } if (type.equalsIgnoreCase("real64")) { return "8"; } return "0"; } private static String getLmcpTypeUpperCase(String type) { if (type.substring(0, 1).equalsIgnoreCase("u")) { return type.substring(0, 2).toUpperCase() + type.substring(2); } return type.substring(0, 1).toUpperCase() + type.substring(1); } private static String getByteBufferTypeUpperCase(String type) { if (type.equalsIgnoreCase("byte")) { return "Byte"; } if (type.equalsIgnoreCase("char")) { return "Byte"; } if (type.equalsIgnoreCase("bool")) { return "Bool"; } if (type.equalsIgnoreCase("int16")) { return "Short"; } if (type.equalsIgnoreCase("uint16")) { return "UShort"; } if (type.equalsIgnoreCase("int32")) { return "Int"; } if (type.equalsIgnoreCase("uint32")) { return "UInt"; } if (type.equalsIgnoreCase("int64")) { return "Long"; } if (type.equalsIgnoreCase("real32")) { return "Float"; } if (type.equalsIgnoreCase("real64")) { return "Double"; } if (type.equalsIgnoreCase("string")) { return "String"; } return "0"; } private static String getCppDefaultVal(MDMInfo[] infos, FieldInfo field) { String type = field.type; if (!field.defaultVal.isEmpty()) { if (type.equalsIgnoreCase("string")) { return "std::string(\"" + field.defaultVal + "\")"; } else if (type.equals("char")) { return "'" + field.defaultVal + "'"; } else if (type.equals("int64")) { return field.defaultVal + "LL"; } else if (type.equals("real32")) { if (field.defaultVal.contains(".")) return field.defaultVal + "f"; else return field.defaultVal + ".f"; } else if (field.isStruct) { if (field.defaultVal.equalsIgnoreCase("null")) { return "0"; } } else if (field.isEnum) { return getSeriesNamespace(infos, field.seriesName) + field.type + "::" + field.defaultVal; } else { return field.defaultVal; } } if (type.equalsIgnoreCase("byte")) { return "0"; } if (type.equalsIgnoreCase("char")) { return "0"; } if (type.equalsIgnoreCase("bool")) { return "false"; } if (type.equalsIgnoreCase("int16") || type.equalsIgnoreCase("int16_t")) { return "0"; } if (type.equalsIgnoreCase("uint16") || type.equalsIgnoreCase("uint16_t")) { return "0"; } if (type.equalsIgnoreCase("int32") || type.equalsIgnoreCase("int32_t")) { return "0"; } if (type.equalsIgnoreCase("uint32") || type.equalsIgnoreCase("uint32_t")) { return "0"; } if (type.equalsIgnoreCase("int64") || type.equalsIgnoreCase("int64_t")) { return "0"; } if (type.equalsIgnoreCase("real32") || type.equalsIgnoreCase("float")) { return "0.f"; } if (type.equalsIgnoreCase("real64") || type.equalsIgnoreCase("double")) { return "0."; } if (type.equalsIgnoreCase("string")) { return "std::string(\"\")"; } if (type.equals(MDMInfo.LMCP_OBJECT_NAME)) { return "nullptr"; } if (field.isEnum) { return getResolvedTypeName(infos, field) + "::" + MDMInfo.getEnumByName(infos, field).entries.get(0).name; } return "new " + getResolvedTypeName(infos, field); // for objects } private static String getArrayTypeName(String type) { if (type.equalsIgnoreCase("byte") || type.equalsIgnoreCase("char") || type.equalsIgnoreCase("bool") || type.equalsIgnoreCase("int16") || type.equalsIgnoreCase("int16_t") || type.equalsIgnoreCase("uint16") || type.equalsIgnoreCase("uint16_t") || type.equalsIgnoreCase("int32") || type.equalsIgnoreCase("int32_t") || type.equalsIgnoreCase("uint32") || type.equalsIgnoreCase("uint32_t") || type.equalsIgnoreCase("int64") || type.equalsIgnoreCase("int64_t") || type.equalsIgnoreCase("real32") || type.equalsIgnoreCase("float") || type.equalsIgnoreCase("real64") || type.equalsIgnoreCase("double") || type.equalsIgnoreCase("string")) { return "PrimitiveArray"; } return type + "Array"; // for objects } private static String getSeriesNamespace(MDMInfo[] infos, String series_name) { MDMInfo i = MDMReader.getMDM(series_name, infos); if (i != null) { return i.namespace.replaceAll("/", "::") + "::"; } return ""; } private static String getSeriesFilepath(MDMInfo[] infos, String series_name) { MDMInfo i = MDMReader.getMDM(series_name, infos); return i.namespace + "/"; } public static Vector<StructInfo> getAllCppSubclasses(MDMInfo[] infos, FieldInfo f) throws Exception { if (f.type.equals(MDMInfo.LMCP_OBJECT_NAME)) { return new Vector<StructInfo>(); } StructInfo i = MDMInfo.getStructByName(infos, f); return getAllCppSubclasses(infos, i); } private static Vector<StructInfo> getAllCppSubclasses(MDMInfo[] infos, StructInfo st) throws Exception { Vector<StructInfo> ret = new Vector<StructInfo>(); if (st.name.equals(MDMInfo.LMCP_OBJECT_NAME)) { return ret; } for (MDMInfo in : infos) { if (st.extends_series.equals(in.seriesName)) { for (int i = 0; i < in.structs.length; i++) { if (in.structs[i].extends_name.equals(st.name)) { ret.add(in.structs[i]); ret.addAll(getAllCppSubclasses(infos, in.structs[i])); } } } } return ret; } private static String getCppNamespace(String namespace) { return namespace.replaceAll("/", "::"); } private static String getResolvedTypeName(MDMInfo[] infos, FieldInfo field) { String type = field.type; if (field.isStruct) { if (field.type.equals(MDMInfo.LMCP_OBJECT_NAME)) { return "avtas::lmcp::Object"; } return getSeriesNamespace(infos, field.seriesName) + type; } else if (field.isEnum) { return getSeriesNamespace(infos, field.seriesName) + type + "::" + type; } else { return getCppTypeName(infos, field); } } static final String block_comment = "\n//"; /** Generates a Globally Unique ID based on RFC 4122. * @return a Globally unique ID with the format: 8-4-4-4-12 digits */ static String makeGUID() { return UUID.randomUUID().toString().toUpperCase(); // Original method Based on code available at www.somacon.com/p113.php // // int n1 = (int) (Math.random() * 65535); // int n2 = (int) (Math.random() * 65535); // int n3 = (int) (Math.random() * 65535); // int n4 = (int) (Math.random() * 4095); // String str5 = Integer.toBinaryString((int) (Math.random() * 65535)); // str5 = str5.substring(0, 5) + "01" + str5.substring(8, str5.length() - 1); // int n5 = Integer.valueOf(str5, 2); // int n6 = (int) (Math.random() * 65535); // int n7 = (int) (Math.random() * 65535); // int n8 = (int) (Math.random() * 65535); // // return String.format("%04x%04x-%04x-%03x4-%04x-%04x%04x%04x", n1, n2, n3, n4, n5, n6, n7, n8).toUpperCase(); } };
46.463712
162
0.458369
682ba0d29a32d917fa4912899d808c0ad2e80ac2
2,357
/* * Copyright (c) 2008-2013 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.cuba.gui.components.actions; import com.haulmont.cuba.gui.ComponentVisitor; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.components.AbstractAction; import com.haulmont.cuba.gui.components.Component; import com.haulmont.cuba.gui.components.Field; import com.haulmont.cuba.gui.components.ListComponent; /** * List action to clear all fields in the specific container. * <p> * Action's behaviour can be customized by providing arguments to constructor or setting properties. * * @author krivopustov * @version $Id$ */ public class FilterClearAction extends AbstractAction { public static final String ACTION_ID = "clear"; protected final ListComponent owner; protected final String containerName; /** * The simplest constructor. The action has default name. * @param owner component containing this action * @param containerName component containing fields to clear */ public FilterClearAction(ListComponent owner, String containerName) { this(owner, containerName, ACTION_ID); } /** * Constructor that allows to specify the action name. * @param owner component containing this action * @param containerName component containing fields to clear * @param id action name */ public FilterClearAction(ListComponent owner, String containerName, String id) { super(id); this.owner = owner; this.containerName = containerName; this.caption = messages.getMainMessage("actions.Clear"); } @Override public void actionPerform(Component component) { Component.Container container = owner.getFrame().getComponent(containerName); ComponentsHelper.walkComponents(container, new ComponentVisitor() { @Override public void visit(Component component, String name) { if (component instanceof Field) { ((Field) component).setValue(null); } } } ); } }
35.712121
101
0.649979
696e035df89722b7f4b95bd61cfe344a5f6d1037
958
package org.assimbly.gateway.service; import org.assimbly.gateway.service.dto.QueueDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; /** * Service Interface for managing {@link org.assimbly.gateway.domain.Queue}. */ public interface QueueService { /** * Save a queue. * * @param queueDTO the entity to save. * @return the persisted entity. */ QueueDTO save(QueueDTO queueDTO); /** * Get all the queues. * * @param pageable the pagination information. * @return the list of entities. */ Page<QueueDTO> findAll(Pageable pageable); /** * Get the "id" queue. * * @param id the id of the entity. * @return the entity. */ Optional<QueueDTO> findOne(Long id); /** * Delete the "id" queue. * * @param id the id of the entity. */ void delete(Long id); }
20.826087
76
0.624217
2a9736b158e4454eb7d7aa1137057c513bded9b6
2,568
package org.drools.task; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.util.Collections; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Embeddable; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import org.drools.task.utils.CollectionUtils; @Embeddable public class Deadlines implements Externalizable { @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "Deadlines_StartDeadLine_Id", nullable = true) private List<Deadline> startDeadlines = Collections.emptyList(); @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "Deadlines_EndDeadLine_Id", nullable = true) private List<Deadline> endDeadlines = Collections.emptyList(); public void writeExternal(ObjectOutput out) throws IOException { CollectionUtils.writeDeadlineList( startDeadlines, out ); CollectionUtils.writeDeadlineList( endDeadlines, out ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { startDeadlines = CollectionUtils.readDeadlinesList( in ); endDeadlines = CollectionUtils.readDeadlinesList( in ); } public List<Deadline> getStartDeadlines() { return startDeadlines; } public void setStartDeadlines(List<Deadline> startDeadlines) { this.startDeadlines = startDeadlines; } public List<Deadline> getEndDeadLines() { return endDeadlines; } public void setEndDeadlines(List<Deadline> endDeadlines) { this.endDeadlines = endDeadlines; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + CollectionUtils.hashCode( endDeadlines ); result = prime * result + CollectionUtils.hashCode( startDeadlines ); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( !(obj instanceof Deadlines) ) return false; Deadlines other = (Deadlines) obj; return CollectionUtils.equals( endDeadlines, other.endDeadlines ) && CollectionUtils.equals( startDeadlines, other.startDeadlines ); } }
33.789474
141
0.650701
dfeaf9b6d593ffb4dc964a9815206d653061a3d2
3,459
/* * 文件名称: WPPageListItem.java * * 编译器: android2.2 * 时间: 上午10:24:57 */ package com.wxiwei.office.wp.control; import com.wxiwei.office.common.ICustomDialog; import com.wxiwei.office.constant.EventConstant; import com.wxiwei.office.fc.pdf.PDFHyperlinkInfo; import com.wxiwei.office.fc.pdf.PDFLib; import com.wxiwei.office.pdf.PDFFind; import com.wxiwei.office.pdf.PDFPageListItem; import com.wxiwei.office.pdf.RepaintAreaInfo; import com.wxiwei.office.simpletext.control.SafeAsyncTask; import com.wxiwei.office.system.IControl; import com.wxiwei.office.system.beans.pagelist.APageListItem; import com.wxiwei.office.system.beans.pagelist.APageListView; import com.wxiwei.office.wp.view.PageRoot; import com.wxiwei.office.wp.view.PageView; import android.R.color; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.ProgressBar; /** * word engine "PageListView" component item * <p> * <p> * Read版本: Read V1.0 * <p> * 作者: ljj8494 * <p> * 日期: 2013-1-8 * <p> * 负责人: ljj8494 * <p> * 负责小组: * <p> * <p> */ public class WPPageListItem extends APageListItem { private static final int BACKGROUND_COLOR = 0xFFFFFFFF; /** * * @param content * @param parentSize */ public WPPageListItem(APageListView listView, IControl control, int pageWidth, int pageHeight) { super(listView, pageWidth, pageHeight); this.control = control; this.pageRoot= (PageRoot)listView.getModel(); this.setBackgroundColor(BACKGROUND_COLOR); } /** * */ public void onDraw(Canvas canvas) { PageView pv = pageRoot.getPageView(pageIndex); if (pv != null) { float zoom = listView.getZoom(); canvas.save(); canvas.translate(-pv.getX() * zoom, -pv.getY() * zoom); pv.drawForPrintMode(canvas, 0, 0, zoom); canvas.restore(); } } /** * * @param pageIndex page index (base 0) * @param pageWidth page width of after scaled * @param pageHeight page height of after scaled */ public void setPageItemRawData(final int pIndex, int pageWidth, int pageHeight) { super.setPageItemRawData(pIndex, pageWidth, pageHeight); //final APageListItem own = this; if ((int)(listView.getZoom() * 100) == 100 || (isInit && pIndex == 0)) { listView.exportImage(this, null); } isInit = false; } /** * added reapint image view */ protected void addRepaintImageView(Bitmap bmp) { postInvalidate(); listView.exportImage(this, null); } /** * remove reapint image view */ protected void removeRepaintImageView() { } /** * */ public void dispose() { super.dispose(); control = null; pageRoot = null; } // private boolean isInit = true; // private PageRoot pageRoot; }
25.065217
98
0.627349
4cd2dd0a4ee16996c544f6d21faa666663c8d6d8
21,680
/* * Copyright (c) 2008-2013, Matthias Mann * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Matthias Mann nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.matthiasmann.twl; import de.matthiasmann.twl.renderer.AnimationState.StateKey; import de.matthiasmann.twl.renderer.MouseCursor; import de.matthiasmann.twl.utils.TintAnimator; /** * A resizable frame. * * <p> * All child widgets (which are not part of the frame itself) cover the complete * inner area {@link #layoutChildFullInnerArea(de.matthiasmann.twl.Widget) }. * </p> * * <p> * The preferred way to use the ResizableFrame is to add a single widget which * will manage the layout of all it's children. {@link DialogLayout} can be used * for this to avoid creating a new class. * </p> * * @author Matthias Mann */ public class ResizableFrame extends Widget { public static final StateKey STATE_FADE = StateKey.get("fade"); public enum ResizableAxis { NONE(false, false), HORIZONTAL(true, false), VERTICAL(false, true), BOTH( true, true); final boolean allowX; final boolean allowY; private ResizableAxis(boolean allowX, boolean allowY) { this.allowX = allowX; this.allowY = allowY; } }; private enum DragMode { NONE("mouseCursor"), EDGE_LEFT("mouseCursor.left"), EDGE_TOP( "mouseCursor.top"), EDGE_RIGHT("mouseCursor.right"), EDGE_BOTTOM( "mouseCursor.bottom"), CORNER_TL("mouseCursor.top-left"), CORNER_TR( "mouseCursor.top-right"), CORNER_BR("mouseCursor.bottom-right"), CORNER_BL( "mouseCursor.bottom-left"), POSITION("mouseCursor.all"); final String cursorName; DragMode(String cursorName) { this.cursorName = cursorName; } } private String title; private final MouseCursor[] cursors; private ResizableAxis resizableAxis = ResizableAxis.BOTH; private boolean draggable = true; private boolean backgroundDraggable; private DragMode dragMode = DragMode.NONE; private int dragStartX; private int dragStartY; private int dragInitialLeft; private int dragInitialTop; private int dragInitialRight; private int dragInitialBottom; private Color fadeColorInactive = Color.WHITE; private int fadeDurationActivate; private int fadeDurationDeactivate; private int fadeDurationShow; private int fadeDurationHide; private TextWidget titleWidget; private int titleAreaTop; private int titleAreaLeft; private int titleAreaRight; private int titleAreaBottom; private boolean hasCloseButton; private Button closeButton; private int closeButtonX; private int closeButtonY; private boolean hasResizeHandle; private Widget resizeHandle; private int resizeHandleX; private int resizeHandleY; private DragMode resizeHandleDragMode; public ResizableFrame() { title = ""; cursors = new MouseCursor[DragMode.values().length]; setCanAcceptKeyboardFocus(true); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; if (titleWidget != null) { titleWidget.setCharSequence(title); } } public ResizableAxis getResizableAxis() { return resizableAxis; } public void setResizableAxis(ResizableAxis resizableAxis) { if (resizableAxis == null) { throw new NullPointerException("resizableAxis"); } this.resizableAxis = resizableAxis; if (resizeHandle != null) { layoutResizeHandle(); } } public boolean isDraggable() { return draggable; } /** * Controls weather the ResizableFrame can be dragged via the title bar or * not, default is true. * * <p> * When set to false the resizing should also be disabled to present a * consistent behavior to the user. * </p> * * @param movable * if dragging via the title bar is allowed - default is true. */ public void setDraggable(boolean movable) { this.draggable = movable; } public boolean isBackgroundDraggable() { return backgroundDraggable; } /** * Controls weather the ResizableFrame can be dragged via the background (eg * space not occupied by any widget or a resizable edge), default is false. * * <p> * This works independent of {@link #setDraggable(boolean) }. * </p> * * @param backgroundDraggable * if dragging via the background is allowed - default is false. * @see #setDraggable(boolean) */ public void setBackgroundDraggable(boolean backgroundDraggable) { this.backgroundDraggable = backgroundDraggable; } public final boolean hasTitleBar() { return titleWidget != null && titleWidget.getParent() == this; } public void addCloseCallback(Runnable cb) { if (closeButton == null) { closeButton = new Button(); closeButton.setTheme("closeButton"); closeButton.setCanAcceptKeyboardFocus(false); add(closeButton); layoutCloseButton(); } closeButton.setVisible(hasCloseButton); closeButton.addCallback(cb); } public void removeCloseCallback(Runnable cb) { if (closeButton != null) { closeButton.removeCallback(cb); closeButton.setVisible(closeButton.hasCallbacks()); } } public int getFadeDurationActivate() { return fadeDurationActivate; } public int getFadeDurationDeactivate() { return fadeDurationDeactivate; } public int getFadeDurationHide() { return fadeDurationHide; } public int getFadeDurationShow() { return fadeDurationShow; } @Override public void setVisible(boolean visible) { if (visible) { TintAnimator tintAnimator = getTintAnimator(); if ((tintAnimator != null && tintAnimator.hasTint()) || !super.isVisible()) { fadeTo(hasKeyboardFocus() ? Color.WHITE : fadeColorInactive, fadeDurationShow); } } else if (super.isVisible()) { fadeToHide(fadeDurationHide); } } /** * Sets the visibility without triggering a fade * * @param visible * the new visibility flag * @see Widget#setVisible(boolean) */ public void setHardVisible(boolean visible) { super.setVisible(visible); } protected void applyThemeResizableFrame(ThemeInfo themeInfo) { for (DragMode m : DragMode.values()) { cursors[m.ordinal()] = themeInfo.getMouseCursor(m.cursorName); } titleAreaTop = themeInfo.getParameter("titleAreaTop", 0); titleAreaLeft = themeInfo.getParameter("titleAreaLeft", 0); titleAreaRight = themeInfo.getParameter("titleAreaRight", 0); titleAreaBottom = themeInfo.getParameter("titleAreaBottom", 0); closeButtonX = themeInfo.getParameter("closeButtonX", 0); closeButtonY = themeInfo.getParameter("closeButtonY", 0); hasCloseButton = themeInfo.getParameter("hasCloseButton", false); hasResizeHandle = themeInfo.getParameter("hasResizeHandle", false); resizeHandleX = themeInfo.getParameter("resizeHandleX", 0); resizeHandleY = themeInfo.getParameter("resizeHandleY", 0); fadeColorInactive = themeInfo.getParameter("fadeColorInactive", Color.WHITE); fadeDurationActivate = themeInfo .getParameter("fadeDurationActivate", 0); fadeDurationDeactivate = themeInfo.getParameter( "fadeDurationDeactivate", 0); fadeDurationShow = themeInfo.getParameter("fadeDurationShow", 0); fadeDurationHide = themeInfo.getParameter("fadeDurationHide", 0); invalidateLayout(); if (super.isVisible() && !hasKeyboardFocus() && (getTintAnimator() != null || !Color.WHITE .equals(fadeColorInactive))) { fadeTo(fadeColorInactive, 0); } } @Override protected void applyTheme(ThemeInfo themeInfo) { super.applyTheme(themeInfo); applyThemeResizableFrame(themeInfo); } @Override protected void updateTintAnimation() { TintAnimator tintAnimator = getTintAnimator(); tintAnimator.update(); if (!tintAnimator.isFadeActive() && tintAnimator.isZeroAlpha()) { setHardVisible(false); } } protected void fadeTo(Color color, int duration) { // System.out.println("Start fade to " + color + " over " + duration + // " ms"); allocateTint().fadeTo(color, duration); if (!super.isVisible() && color.getAlpha() != 0) { setHardVisible(true); } } protected void fadeToHide(int duration) { if (duration <= 0) { setHardVisible(false); } else { allocateTint().fadeToHide(duration); } } private TintAnimator allocateTint() { TintAnimator tintAnimator = getTintAnimator(); if (tintAnimator == null) { tintAnimator = new TintAnimator( new TintAnimator.AnimationStateTimeSource( getAnimationState(), STATE_FADE)); setTintAnimator(tintAnimator); if (!super.isVisible()) { // we start with TRANSPARENT when hidden tintAnimator.fadeToHide(0); } } return tintAnimator; } protected boolean isFrameElement(Widget widget) { return widget == titleWidget || widget == closeButton || widget == resizeHandle; } @Override protected void layout() { int minWidth = getMinWidth(); int minHeight = getMinHeight(); if (getWidth() < minWidth || getHeight() < minHeight) { int width = Math.max(getWidth(), minWidth); int height = Math.max(getHeight(), minHeight); if (getParent() != null) { int x = Math.min(getX(), getParent().getInnerRight() - width); int y = Math.min(getY(), getParent().getInnerBottom() - height); setPosition(x, y); } setSize(width, height); } for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { layoutChildFullInnerArea(child); } } layoutTitle(); layoutCloseButton(); layoutResizeHandle(); } protected void layoutTitle() { int titleX = getTitleX(titleAreaLeft); int titleY = getTitleY(titleAreaTop); int titleWidth = Math.max(0, getTitleX(titleAreaRight) - titleX); int titleHeight = Math.max(0, getTitleY(titleAreaBottom) - titleY); if (titleAreaLeft != titleAreaRight && titleAreaTop != titleAreaBottom) { if (titleWidget == null) { titleWidget = new TextWidget(getAnimationState()); titleWidget.setTheme("title"); titleWidget .setMouseCursor(cursors[DragMode.POSITION.ordinal()]); titleWidget.setCharSequence(title); titleWidget.setClip(true); } if (titleWidget.getParent() == null) { insertChild(titleWidget, 0); } titleWidget.setPosition(titleX, titleY); titleWidget.setSize(titleWidth, titleHeight); } else if (titleWidget != null && titleWidget.getParent() == this) { titleWidget.destroy(); removeChild(titleWidget); } } protected void layoutCloseButton() { if (closeButton != null) { closeButton.adjustSize(); closeButton.setPosition(getTitleX(closeButtonX), getTitleY(closeButtonY)); closeButton .setVisible(closeButton.hasCallbacks() && hasCloseButton); } } protected void layoutResizeHandle() { if (hasResizeHandle && resizeHandle == null) { resizeHandle = new Widget(getAnimationState(), true); resizeHandle.setTheme("resizeHandle"); super.insertChild(resizeHandle, 0); } if (resizeHandle != null) { if (resizeHandleX > 0) { if (resizeHandleY > 0) { resizeHandleDragMode = DragMode.CORNER_TL; } else { resizeHandleDragMode = DragMode.CORNER_TR; } } else if (resizeHandleY > 0) { resizeHandleDragMode = DragMode.CORNER_BL; } else { resizeHandleDragMode = DragMode.CORNER_BR; } resizeHandle.adjustSize(); resizeHandle.setPosition(getTitleX(resizeHandleX), getTitleY(resizeHandleY)); resizeHandle.setVisible(hasResizeHandle && resizableAxis == ResizableAxis.BOTH); } else { resizeHandleDragMode = DragMode.NONE; } } @Override protected void keyboardFocusGained() { fadeTo(Color.WHITE, fadeDurationActivate); } @Override protected void keyboardFocusLost() { if (!hasOpenPopups() && super.isVisible()) { fadeTo(fadeColorInactive, fadeDurationDeactivate); } } @Override public int getMinWidth() { int minWidth = super.getMinWidth(); for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { minWidth = Math.max(minWidth, child.getMinWidth() + getBorderHorizontal()); } } if (hasTitleBar() && titleAreaRight < 0) { minWidth = Math.max(minWidth, titleWidget.getPreferredWidth() + titleAreaLeft - titleAreaRight); } return minWidth; } @Override public int getMinHeight() { int minHeight = super.getMinHeight(); for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { minHeight = Math.max(minHeight, child.getMinHeight() + getBorderVertical()); } } return minHeight; } @Override public int getMaxWidth() { int maxWidth = super.getMaxWidth(); for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { int aMaxWidth = child.getMaxWidth(); if (aMaxWidth > 0) { aMaxWidth += getBorderHorizontal(); if (maxWidth == 0 || aMaxWidth < maxWidth) { maxWidth = aMaxWidth; } } } } return maxWidth; } @Override public int getMaxHeight() { int maxHeight = super.getMaxHeight(); for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { int aMaxHeight = child.getMaxHeight(); if (aMaxHeight > 0) { aMaxHeight += getBorderVertical(); if (maxHeight == 0 || aMaxHeight < maxHeight) { maxHeight = aMaxHeight; } } } } return maxHeight; } @Override public int getPreferredInnerWidth() { int prefWidth = 0; for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { prefWidth = Math.max(prefWidth, child.getPreferredWidth()); } } return prefWidth; } @Override public int getPreferredWidth() { int prefWidth = super.getPreferredWidth(); if (hasTitleBar() && titleAreaRight < 0) { prefWidth = Math.max(prefWidth, titleWidget.getPreferredWidth() + titleAreaLeft - titleAreaRight); } return prefWidth; } @Override public int getPreferredInnerHeight() { int prefHeight = 0; for (int i = 0, n = getNumChildren(); i < n; i++) { Widget child = getChild(i); if (!isFrameElement(child)) { prefHeight = Math.max(prefHeight, child.getPreferredHeight()); } } return prefHeight; } @Override public void adjustSize() { layoutTitle(); super.adjustSize(); } private int getTitleX(int offset) { return (offset < 0) ? getRight() + offset : getX() + offset; } private int getTitleY(int offset) { return (offset < 0) ? getBottom() + offset : getY() + offset; } @Override protected boolean handleEvent(Event evt) { boolean isMouseExit = evt.getType() == Event.Type.MOUSE_EXITED; if (isMouseExit && resizeHandle != null && resizeHandle.isVisible()) { resizeHandle.getAnimationState().setAnimationState( TextWidget.STATE_HOVER, false); } if (dragMode != DragMode.NONE) { if (evt.isMouseDragEnd()) { dragMode = DragMode.NONE; } else if (evt.getType() == Event.Type.MOUSE_DRAGGED) { handleMouseDrag(evt); } return true; } if (!isMouseExit && resizeHandle != null && resizeHandle.isVisible()) { resizeHandle.getAnimationState().setAnimationState( TextWidget.STATE_HOVER, resizeHandle.isMouseInside(evt)); } if (!evt.isMouseDragEvent()) { if (evt.getType() == Event.Type.MOUSE_BTNDOWN && evt.getMouseButton() == Event.MOUSE_LBUTTON && handleMouseDown(evt)) { return true; } } if (super.handleEvent(evt)) { return true; } return evt.isMouseEvent(); } @Override public MouseCursor getMouseCursor(Event evt) { DragMode cursorMode = dragMode; if (cursorMode == DragMode.NONE) { cursorMode = getDragMode(evt.getMouseX(), evt.getMouseY()); if (cursorMode == DragMode.NONE) { return getMouseCursor(); } } return cursors[cursorMode.ordinal()]; } private DragMode getDragMode(int mx, int my) { boolean left = mx < getInnerX(); boolean right = mx >= getInnerRight(); boolean top = my < getInnerY(); boolean bot = my >= getInnerBottom(); if (hasTitleBar()) { if (titleWidget.isInside(mx, my)) { if (draggable) { return DragMode.POSITION; } else { return DragMode.NONE; } } top = my < titleWidget.getY(); } if (closeButton != null && closeButton.isVisible() && closeButton.isInside(mx, my)) { return DragMode.NONE; } if (resizableAxis == ResizableAxis.NONE) { if (backgroundDraggable) { return DragMode.POSITION; } return DragMode.NONE; } if (resizeHandle != null && resizeHandle.isVisible() && resizeHandle.isInside(mx, my)) { return resizeHandleDragMode; } if (!resizableAxis.allowX) { left = false; right = false; } if (!resizableAxis.allowY) { top = false; bot = false; } if (left) { if (top) { return DragMode.CORNER_TL; } if (bot) { return DragMode.CORNER_BL; } return DragMode.EDGE_LEFT; } if (right) { if (top) { return DragMode.CORNER_TR; } if (bot) { return DragMode.CORNER_BR; } return DragMode.EDGE_RIGHT; } if (top) { return DragMode.EDGE_TOP; } if (bot) { return DragMode.EDGE_BOTTOM; } if (backgroundDraggable) { return DragMode.POSITION; } return DragMode.NONE; } private boolean handleMouseDown(Event evt) { final int mx = evt.getMouseX(); final int my = evt.getMouseY(); dragStartX = mx; dragStartY = my; dragInitialLeft = getX(); dragInitialTop = getY(); dragInitialRight = getRight(); dragInitialBottom = getBottom(); dragMode = getDragMode(mx, my); return dragMode != DragMode.NONE; } private void handleMouseDrag(Event evt) { final int dx = evt.getMouseX() - dragStartX; final int dy = evt.getMouseY() - dragStartY; int minWidth = getMinWidth(); int minHeight = getMinHeight(); int maxWidth = getMaxWidth(); int maxHeight = getMaxHeight(); // make sure max size is not smaller then min size if (maxWidth > 0 && maxWidth < minWidth) { maxWidth = minWidth; } if (maxHeight > 0 && maxHeight < minHeight) { maxHeight = minHeight; } int left = dragInitialLeft; int top = dragInitialTop; int right = dragInitialRight; int bottom = dragInitialBottom; switch (dragMode) { case CORNER_BL: case CORNER_TL: case EDGE_LEFT: left = Math.min(left + dx, right - minWidth); if (maxWidth > 0) { left = Math.max(left, Math.min(dragInitialLeft, right - maxWidth)); } break; case CORNER_BR: case CORNER_TR: case EDGE_RIGHT: right = Math.max(right + dx, left + minWidth); if (maxWidth > 0) { right = Math.min(right, Math.max(dragInitialRight, left + maxWidth)); } break; case POSITION: if (getParent() != null) { int minX = getParent().getInnerX(); int maxX = getParent().getInnerRight(); int width = dragInitialRight - dragInitialLeft; left = Math.max(minX, Math.min(maxX - width, left + dx)); right = Math.min(maxX, Math.max(minX + width, right + dx)); } else { left += dx; right += dx; } break; } switch (dragMode) { case CORNER_TL: case CORNER_TR: case EDGE_TOP: top = Math.min(top + dy, bottom - minHeight); if (maxHeight > 0) { top = Math.max(top, Math.min(dragInitialTop, bottom - maxHeight)); } break; case CORNER_BL: case CORNER_BR: case EDGE_BOTTOM: bottom = Math.max(bottom + dy, top + minHeight); if (maxHeight > 0) { bottom = Math.min(bottom, Math.max(dragInitialBottom, top + maxHeight)); } break; case POSITION: if (getParent() != null) { int minY = getParent().getInnerY(); int maxY = getParent().getInnerBottom(); int height = dragInitialBottom - dragInitialTop; top = Math.max(minY, Math.min(maxY - height, top + dy)); bottom = Math.min(maxY, Math.max(minY + height, bottom + dy)); } else { top += dy; bottom += dy; } break; } setArea(top, left, right, bottom); } private void setArea(int top, int left, int right, int bottom) { Widget p = getParent(); if (p != null) { top = Math.max(top, p.getInnerY()); left = Math.max(left, p.getInnerX()); right = Math.min(right, p.getInnerRight()); bottom = Math.min(bottom, p.getInnerBottom()); } setPosition(left, top); setSize(Math.max(getMinWidth(), right - left), Math.max(getMinHeight(), bottom - top)); } }
26.998755
80
0.686485
1b4ff67a976a281bf4950bdcc3e4c54783182426
2,301
import static java.lang.Math.pow; import java.util.Arrays; import io.jenetics.Genotype; import io.jenetics.Mutator; import io.jenetics.engine.Codec; import io.jenetics.engine.Engine; import io.jenetics.engine.EvolutionResult; import io.jenetics.ext.SingleNodeCrossover; import io.jenetics.ext.util.Tree; import io.jenetics.prog.ProgramChromosome; import io.jenetics.prog.ProgramGene; import io.jenetics.prog.op.EphemeralConst; import io.jenetics.prog.op.MathOp; import io.jenetics.prog.op.Op; import io.jenetics.prog.op.Var; import io.jenetics.util.ISeq; import io.jenetics.util.RandomRegistry; public class SymbolicRegression { // Sample data created with 4*x^3 - 3*x^2 + x static final double[][] SAMPLES = new double[][] { {-1.0, -8.0000}, {-0.9, -6.2460}, {-0.8, -4.7680}, {-0.7, -3.5420}, {-0.6, -2.5440}, {-0.5, -1.7500}, {-0.4, -1.1360}, {-0.3, -0.6780}, {-0.2, -0.3520}, {-0.1, -0.1340}, {0.0, 0.0000}, {0.1, 0.0740}, {0.2, 0.1120}, {0.3, 0.1380}, {0.4, 0.1760}, {0.5, 0.2500}, {0.6, 0.3840}, {0.7, 0.6020}, {0.8, 0.9280}, {0.9, 1.3860}, {1.0, 2.0000} }; // Definition of the operations. static final ISeq<Op<Double>> OPERATIONS = ISeq.of( MathOp.ADD, MathOp.SUB, MathOp.MUL ); // Definition of the terminals. static final ISeq<Op<Double>> TERMINALS = ISeq.of( Var.of("x", 0), EphemeralConst.of(() -> (double)RandomRegistry .getRandom().nextInt(10)) ); static double error(final ProgramGene<Double> program) { return Arrays.stream(SAMPLES) .mapToDouble(sample -> pow(sample[1] - program.eval(sample[0]), 2) + program.size()*0.00001) .sum(); } static final Codec<ProgramGene<Double>, ProgramGene<Double>> CODEC = Codec.of( Genotype.of(ProgramChromosome.of( 5, ch -> ch.getRoot().size() <= 50, OPERATIONS, TERMINALS )), Genotype::getGene ); public static void main(final String[] args) { final Engine<ProgramGene<Double>, Double> engine = Engine .builder(SymbolicRegression::error, CODEC) .minimizing() .alterers( new SingleNodeCrossover<>(), new Mutator<>()) .build(); final ProgramGene<Double> program = engine.stream() .limit(100) .collect(EvolutionResult.toBestGenotype()) .getGene(); System.out.println(Tree.toDottyString(program)); } }
23.242424
61
0.662321
a93bf70d43906f215b030ab150f6723765f1f1ed
2,778
package org.smartrplace.contest.app.profiletaker; import org.ogema.core.application.ApplicationManager; import org.ogema.core.logging.OgemaLogger; import org.ogema.core.resourcemanager.AccessPriority; import org.ogema.core.resourcemanager.pattern.ResourcePatternAccess; import org.smartrplace.contest.app.profiletaker.config.PowervisProfileTakerConfig; import de.iwes.util.resource.ResourceHelper; import org.smartrplace.contest.app.profiletaker.patternlistener.ElectricityMeterListener; import org.smartrplace.contest.app.profiletaker.pattern.ElectricityMeterPattern; // here the controller logic is implemented public class PowervisProfileTakerController { public OgemaLogger log; public ApplicationManager appMan; private ResourcePatternAccess advAcc; public PowervisProfileTakerConfig appConfigData; public PowervisProfileTakerController(ApplicationManager appMan) { this.appMan = appMan; this.log = appMan.getLogger(); this.advAcc = appMan.getResourcePatternAccess(); initConfigurationResource(); initDemands(); } public ElectricityMeterListener electricityMeterListener; /* * This app uses a central configuration resource, which is accessed here */ private void initConfigurationResource() { String configResourceDefaultName = PowervisProfileTakerConfig.class.getSimpleName().substring(0, 1).toLowerCase()+PowervisProfileTakerConfig.class.getSimpleName().substring(1); appConfigData = appMan.getResourceAccess().getResource(configResourceDefaultName); if (appConfigData != null) { // resource already exists (appears in case of non-clean start) appMan.getLogger().debug("{} started with previously-existing config resource", getClass().getName()); } else { appConfigData = (PowervisProfileTakerConfig) appMan.getResourceManagement().createResource(configResourceDefaultName, PowervisProfileTakerConfig.class); appConfigData.activate(true); appMan.getLogger().debug("{} started with new config resource", getClass().getName()); } appConfigData.availablePrograms().create(); } /* * register ResourcePatternDemands. The listeners will be informed about new and disappearing * patterns in the OGEMA resource tree */ public void initDemands() { electricityMeterListener = new ElectricityMeterListener(this); advAcc.addPatternDemand(ElectricityMeterPattern.class, electricityMeterListener, AccessPriority.PRIO_LOWEST); } public void close() { advAcc.removePatternDemand(ElectricityMeterPattern.class, electricityMeterListener); } /* * if the app needs to consider dependencies between different pattern types, * they can be processed here. */ public void processInterdependies() { // TODO Auto-generated method stub } }
38.583333
178
0.784377
1a833a4d8206924e5604848b97dc8a2816e9c66a
126
package com.cloudata.structured; public interface Listener<V> { public boolean next(V value); public void done(); }
15.75
33
0.706349
6c3b89cf9d831406efc7e7fc49e399679c81420b
978
package org.basex.query.func.index; import static org.basex.util.Token.*; import org.basex.data.*; import org.basex.index.*; import org.basex.index.query.*; import org.basex.query.*; import org.basex.query.iter.*; import org.basex.query.value.*; /** * Function implementation. * * @author BaseX Team 2005-20, BSD License * @author Christian Gruen */ public class IndexElementNames extends IndexFn { @Override public final Iter iter(final QueryContext qc) throws QueryException { final Data data = checkData(qc); final IndexType type = type(); return entries(type == IndexType.ELEMNAME ? data.elemNames : data.attrNames, new IndexEntries(EMPTY, type)); } @Override public final Value value(final QueryContext qc) throws QueryException { return iter(qc).value(qc, this); } /** * Returns the index type (overwritten by implementing functions). * @return index type */ IndexType type() { return IndexType.ELEMNAME; } }
24.45
80
0.706544
95ed4f7e72a6482015936b02fff4c4f8000cfe08
15,822
package com.github.masonm.wiremock; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.common.Json; import com.github.tomakehurst.wiremock.testsupport.WireMockResponse; import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.skyscreamer.jsonassert.JSONCompareMode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHeader; import static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson; import static java.net.HttpURLConnection.HTTP_OK; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertThat; public class SnapshotAcceptanceTest { private WireMockServer wireMockServer; private WireMockServer proxyingService; private WireMockTestClient proxyingTestClient; @Before public void init() throws IOException { wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); wireMockServer.start(); File root = Files.createTempDirectory("wiremock").toFile(); new File(root, MAPPINGS_ROOT).mkdirs(); proxyingService = new WireMockServer(wireMockConfig() .dynamicPort() .extensions("com.github.masonm.wiremock.SnapshotExtension") .withRootDirectory(root.getAbsolutePath()) ); proxyingService.start(); proxyingService.stubFor(proxyAllTo("http://localhost:" + wireMockServer.port())); proxyingTestClient = new WireMockTestClient(proxyingService.port()); } @After public void cleanup() { wireMockServer.stop(); proxyingService.stop(); } private static final String DEFAULT_SNAPSHOT_RESPONSE = "[ \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar/baz\", \n" + " \"method\" : \"GET\" \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " }, \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar\", \n" + " \"method\" : \"GET\" \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " } \n" + " ] "; @Test public void returnsRequestsWithDefaultOptions() throws Exception { wireMockServer.stubFor(get(anyUrl()).willReturn(ok())); proxyingTestClient.get("/foo/bar", withHeader("A", "B")); proxyingTestClient.get("/foo/bar/baz", withHeader("A", "B")); assertThat( snapshot("{}"), equalToJson(DEFAULT_SNAPSHOT_RESPONSE, JSONCompareMode.STRICT_ORDER) ); } private static final String FILTER_BY_REQUEST_PATTERN_SNAPSHOT_REQUEST = "{ \n" + " \"outputFormat\": \"full\", \n" + " \"persist\": \"false\", \n" + " \"filters\": { \n" + " \"urlPattern\": \"/foo.*\", \n" + " \"headers\": { \n" + " \"A\": { \"equalTo\": \"B\" } \n" + " } \n" + " } \n" + "} "; private static final String FILTER_BY_REQUEST_PATTERN_SNAPSHOT_RESPONSE = "[ \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar/baz\", \n" + " \"method\" : \"GET\" \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " }, \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar\", \n" + " \"method\" : \"GET\" \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " } \n" + " ] "; @Test public void returnsFilteredRequestsWithJustRequestPatternsAndFullOutputFormat() throws Exception { wireMockServer.stubFor(get(anyUrl()).willReturn(ok())); // Matches both proxyingTestClient.get("/foo/bar", withHeader("A", "B")); // Fails header match proxyingTestClient.get("/foo"); // Fails URL match proxyingTestClient.get("/bar", withHeader("A", "B")); // Fails header match proxyingTestClient.get("/foo/", withHeader("A", "C")); // Matches both proxyingTestClient.get("/foo/bar/baz", withHeader("A", "B")); assertThat( snapshot(FILTER_BY_REQUEST_PATTERN_SNAPSHOT_REQUEST), equalToJson(FILTER_BY_REQUEST_PATTERN_SNAPSHOT_RESPONSE, JSONCompareMode.STRICT_ORDER) ); } private static final String FILTER_BY_REQUEST_PATTERN_AND_IDS_SNAPSHOT_REQUEST_TEMPLATE = "{ \n" + " \"outputFormat\": \"full\", \n" + " \"persist\": \"false\", \n" + " \"filters\": { \n" + " \"ids\": [ %s, %s ], \n" + " \"urlPattern\": \"/foo.*\" \n" + " } \n" + "} "; private static final String FILTER_BY_REQUEST_PATTERN_AND_IDS_SNAPSHOT_RESPONSE = "[ \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar\", \n" + " \"method\" : \"GET\" \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " } \n" + " ] "; @Test public void returnsFilteredRequestsWithRequestPatternAndIdsWithFullOutputFormat() { wireMockServer.stubFor(get(anyUrl()).willReturn(ok())); // Matches both proxyingTestClient.get("/foo/bar"); // Fails URL match proxyingTestClient.get("/bar"); // Fails ID match proxyingTestClient.get("/foo"); String requestsJson = proxyingTestClient.get("/__admin/requests").content(); JsonNode requestsNode = Json.node(requestsJson).path("requests"); String request = String.format(FILTER_BY_REQUEST_PATTERN_AND_IDS_SNAPSHOT_REQUEST_TEMPLATE, requestsNode.get(2).get("id"), requestsNode.get(1).get("id") ); assertThat( snapshot(request), equalToJson(FILTER_BY_REQUEST_PATTERN_AND_IDS_SNAPSHOT_RESPONSE, JSONCompareMode.STRICT_ORDER) ); } private static final String CAPTURE_HEADERS_SNAPSHOT_REQUEST = "{ \n" + " \"outputFormat\": \"full\", \n" + " \"persist\": \"false\", \n" + " \"captureHeaders\": { \n" + " \"Accept\": { \n" + " \"anything\": true \n" + " }, \n" + " \"X-NoMatch\": { \n" + " \"equalTo\": \"!\" \n" + " } \n" + " } \n" + "} "; private static final String CAPTURE_HEADERS_SNAPSHOT_RESPONSE = "[ \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo/bar\", \n" + " \"method\" : \"PUT\", \n" + " \"headers\": { \n" + " \"Accept\": { \n" + " \"equalTo\": \"B\" \n" + " } \n" + " } \n" + " }, \n" + " \"response\" : { \n" + " \"status\" : 200 \n" + " } \n" + " } \n" + "] "; @Test public void returnsStubMappingWithCapturedHeaders() { wireMockServer.stubFor(put(anyUrl()).willReturn(ok())); proxyingTestClient.put("/foo/bar", withHeader("A", "B"), withHeader("Accept", "B"), withHeader("X-NoMatch", "should be ignored") ); String actual = snapshot(CAPTURE_HEADERS_SNAPSHOT_REQUEST); assertThat(actual, equalToJson(CAPTURE_HEADERS_SNAPSHOT_RESPONSE, JSONCompareMode.STRICT_ORDER)); assertFalse(actual.contains("X-NoMatch")); } private static final String REPEATS_AS_SCENARIOS_SNAPSHOT_REQUEST = "{ \n" + " \"outputFormat\": \"full\", \n" + " \"persist\": \"false\", \n" + " \"repeatsAsScenarios\": \"true\" \n" + "} "; private static final String REPEATS_AS_SCENARIOS_SNAPSHOT_RESPONSE = "[ \n" + " { \n" + " \"scenarioName\" : \"scenario-bar-baz\", \n" + " \"requiredScenarioState\" : \"Started\", \n" + " \"request\" : { \n" + " \"url\" : \"/bar/baz\", \n" + " \"method\" : \"GET\" \n" + " } \n" + " }, \n" + " { \n" + " \"request\" : { \n" + " \"url\" : \"/foo\", \n" + " \"method\" : \"GET\" \n" + " } \n" + " }, \n" + " { \n" + " \"scenarioName\" : \"scenario-bar-baz\", \n" + " \"requiredScenarioState\" : \"Started\", \n" + " \"newScenarioState\" : \"scenario-bar-baz-2\", \n" + " \"request\" : { \n" + " \"url\" : \"/bar/baz\", \n" + " \"method\" : \"GET\" \n" + " } \n" + " } \n" + " ] "; @Test public void returnsStubMappingsWithScenariosForRepeatedRequests() { wireMockServer.stubFor(get(anyUrl()).willReturn(ok())); proxyingTestClient.get("/bar/baz"); proxyingTestClient.get("/foo"); proxyingTestClient.get("/bar/baz"); assertThat( snapshot(REPEATS_AS_SCENARIOS_SNAPSHOT_REQUEST), equalToJson(REPEATS_AS_SCENARIOS_SNAPSHOT_RESPONSE, JSONCompareMode.STRICT_ORDER) ); } private String snapshot(String snapshotSpecJson) { WireMockResponse response = proxyingTestClient.postJson("/__admin/recordings/snapshot", snapshotSpecJson); if (response.statusCode() != HTTP_OK) { throw new RuntimeException("Returned status code was " + response.statusCode()); } return response.content(); } }
53.09396
114
0.336051
3ed6895ec8dd28876670891824ed6b94f08c9b74
1,564
package edu.cs4730.VideoCap; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.util.Log; public class VideoCapture extends Activity implements OnClickListener { boolean recording = false; CaptureSurface cameraView = null; String outputFile = "/sdcard/videoexample.mp4"; private static final String Tag = "VideoCapture"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); cameraView = (CaptureSurface) findViewById(R.id.CameraView); cameraView.setClickable(true); cameraView.setOnClickListener(this); } @Override public void onClick(View v) { if (recording) { Log.d(Tag,"Calling stopRecording in CaptureSurface"); cameraView.stopRecording(); recording = false; Log.d(Tag,"finished, now calling native viewer"); Uri data = Uri.parse(outputFile); Intent intent = new Intent(android.content.Intent.ACTION_VIEW, data); intent.setDataAndType(data, "video/mp4"); //This intent fails with a No activity found to handle intent. This used to work and still does in 2.3.3, but fails above it. //no fix could be found that worked. So, I'm leaving it commented out. //startActivity(intent); Log.d(Tag,"Native viewer should be playing, we are done."); finish(); } else { recording = true; Log.d(Tag,"Calling startRecording in CaptureSurface"); cameraView.startRecording(); } } }
30.666667
129
0.743606
402c15b21ff5114d1a57d03269171784de6e7e34
111
package com.example.bookstore; import android.app.Activity; public class QueryDataBase extends Activity{ }
13.875
45
0.801802
200e48f1d357cd8068101258b99d3b3a5fae725e
1,422
package org.vaadin.erik; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.UI; import com.vaadin.flow.server.VaadinSession; /** * @author [email protected] * @since 24/01/2020 */ public class SecurityService { private static final String USER_ATTRIBUTE = "SecurityService.User"; private static final String USERNAME = "admin"; private static final String PASSWORD = "password"; private static SecurityService instance; private SecurityService() {} public static SecurityService getInstance() { if (instance == null) { instance = new SecurityService(); } return instance; } public boolean isAuthenticated() { return VaadinSession.getCurrent() != null && VaadinSession.getCurrent().getAttribute(USER_ATTRIBUTE) != null; } public boolean authenticate(String username, String password) { if (USERNAME.equals(username) && PASSWORD.equals(password)) { VaadinSession.getCurrent().setAttribute(USER_ATTRIBUTE, username); return true; } return false; } public void logOut() { VaadinSession.getCurrent().close(); VaadinSession.getCurrent().getSession().invalidate(); UI.getCurrent().navigate(LoginView.class); } public Class<? extends Component> getDefaultView() { return MainView.class; } }
27.346154
80
0.660338
f63a1a33f33f303bcf0bab4e5e1cb0f7bcf4bee1
358
package zhushen.com.shejimoshi.leetcode; /** * Created by Zhushen on 2018/9/11. */ public class titleToNumber { public int titleToNumber(String s) { int result = 0; for (int i = 0; i <s.length() ; i++) { int x = s.charAt(i) - 'A' + 1; result*=26; result+=x; } return result; } }
21.058824
46
0.505587
045e04f7d01d3ae78611c44c7d55d0ea71567160
307
package org.apache.poi.ss.usermodel.charts; public enum AxisOrientation { MAX_MIN("MAX_MIN", 0), MIN_MAX("MIN_MAX", 1); // $FF: synthetic field private static final AxisOrientation[] $VALUES = new AxisOrientation[]{MAX_MIN, MIN_MAX}; private AxisOrientation(String var1, int var2) {} }
20.466667
92
0.70684
6c033292050a83b9f786c095f52fa093da3c6e68
1,039
// Driver code for LP4, part f // Do not rename this file or move it away from cs6301/g?? // Change following line to your group number. Make no other changes. package cs6301.g26; import cs6301.g00.Graph; import cs6301.g00.Graph.Vertex; public class LP4f { static int VERBOSE = 0; public static void main(String[] args) { if(args.length > 0) { VERBOSE = Integer.parseInt(args[0]); } java.util.Scanner in = new java.util.Scanner(System.in); Graph g = Graph.readGraph(in); int source = in.nextInt(); java.util.HashMap<Vertex,Integer> map = new java.util.HashMap<>(); for(Vertex u: g) { map.put(u, in.nextInt()); } java.util.LinkedList<Vertex> list = new java.util.LinkedList<>(); cs6301.g00.Timer t = new cs6301.g00.Timer(); LP4 handle = new LP4(g, g.getVertex(source)); int result = handle.reward(map, list); if(VERBOSE > 0) { LP4.printGraph(g, map, g.getVertex(source), null, 0); } System.out.println(result); for(Vertex u: list) { System.out.print(u + " "); } System.out.println("\n" + t.end()); } }
31.484848
74
0.674687
4d9d9fc9472223ce2a51a6c116e56988f2ce0276
3,061
package volume; import bijnum.*; import ij.*; /** * Plugin containing methods to equalize imageas and volumes. * It is mainly useful to correct vignetting, i.e. anisotropic nonlinear illumination differences over the retinal image. * * Copyright (c) 1999-2003, Michael Abramoff. All rights reserved. * @author: Michael Abramoff * * Small print: * Permission to use, copy, modify and distribute this version of this software or any parts * of it and its documentation or any parts of it ("the software"), for any purpose is * hereby granted, provided that the above copyright notice and this permission notice * appear intact in all copies of the software and that you do not sell the software, * or include the software in a commercial package. * The release of this software into the public domain does not imply any obligation * on the part of the author to release future versions into the public domain. * The author is free to make upgraded or improved versions of the software available * for a fee or commercially only. * Commercial licensing of the software is available by contacting the author. * THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */ public class Equalize { private final static int DEFAULTWINDOWSIZE = 20; public static int getDefaultWindowSize() { return DEFAULTWINDOWSIZE; } /** * Perform sliding window averaging on image. Does NOT modify image. * center will be the average value of the equalized image. * Implements: * I(x) = I(x) + m - Iavg(x, w) * where Iavg(x,w) is the average intensity around x, and w the window size. * Hoover, Goldbaum, IEEE TMI 22,8, pp 955, 2003. * Can process masked images, where non-valid pixels have been set to NaN. * * @param image a float[] with the image vector. * @param width the width of image in pixels. * @param center a float value relative to which all pixels are equalized. * @param windowSize the size of the sliding windows in pixels. * @return a float[] with the equalized version of image. */ public static float [] sliding(float [] image, int width, float center, int windowSize, boolean doShowProgress) { float [] equalized = new float[image.length]; int height = image.length / width; for (int y = 0; y < height; y++) { if (doShowProgress) IJ.showProgress(y, height); for (int x = 0; x < width; x++) { float iPixel = image[y*width+x]; float aggr = 0; int n = 0; for (int j = -windowSize/2; j < windowSize/2; j++) for (int i = -windowSize/2; i < windowSize/2; i++) { int q = y + j; if (q < 0) q = 0; if (q >= height) q = height-1; int p = x + i; if (p < 0) p = 0; if (p >= width) p = width-1; float pixel = image[q*width+p]; if (pixel != Float.NaN) { aggr += pixel; n++; } } equalized[y*width+x] = iPixel + center - aggr / n; } } return equalized; } }
38.2625
121
0.682457
6b5a1f1d443e85f7eaaf6f97affd20b9e0c3a8ca
495
package com.example.demo.utils; import org.elasticsearch.client.transport.TransportClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; /** * @Author: fwb * @Date: 2019/2/27 17:09 */ public class EsTest { private static Logger LOG = LoggerFactory.getLogger(EsTest.class); @Resource(name = "client") private static TransportClient client; public static void main(String[] args) { System.out.println(client); } }
20.625
70
0.715152
316534b54b101161529a88e7e7b3cfc33206c066
1,256
/** * Project Name:aescContract * File Name:TyhtServiceImpl.java * Package Name:com.aesc.service.impl * Date:2017年8月17日上午9:59:38 * Copyright (c) 2017, [email protected] All Rights Reserved. * */ package com.aesc.service.impl; import java.util.List; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import com.aesc.dao.TyhtDao; import com.aesc.pojo.Tyht; import com.aesc.service.TyhtService; /** * ClassName:TyhtServiceImpl <br/> * Function: ADD FUNCTION. <br/> * Reason: ADD REASON. <br/> * Date: 2017年8月17日 上午9:59:38 <br/> * @author Dawn Chen * @version * @since JDK 1.8 * @see */ @Transactional @Service("TyhtService") public class TyhtServiceImpl implements TyhtService { @Resource private TyhtDao tyhtDao; @Override public void saveTyht(Tyht tyht) { tyhtDao.saveTyht(tyht); } @Override public List<Tyht> queryTyht() { return this.tyhtDao.queryTyht(); } @Override public Tyht queryTyhtById(int contract_id) { return this.tyhtDao.queryTyhtById(contract_id); } @Override public boolean updateTyht(Tyht tyht) { return this.tyhtDao.updateTyht(tyht); } }
20.258065
63
0.687102
356e8a32b5cbe9d8047efcea2f9c1729efde95b2
1,642
package com.netsuite.webservices.platform.common.types; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LandedCostSource. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LandedCostSource"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="_manual"/&gt; * &lt;enumeration value="_otherTransaction"/&gt; * &lt;enumeration value="_otherTransactionExcludeTax"/&gt; * &lt;enumeration value="_thisTransaction"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "LandedCostSource", namespace = "urn:types.common_2014_2.platform.webservices.netsuite.com") @XmlEnum public enum LandedCostSource { @XmlEnumValue("_manual") MANUAL("_manual"), @XmlEnumValue("_otherTransaction") OTHER_TRANSACTION("_otherTransaction"), @XmlEnumValue("_otherTransactionExcludeTax") OTHER_TRANSACTION_EXCLUDE_TAX("_otherTransactionExcludeTax"), @XmlEnumValue("_thisTransaction") THIS_TRANSACTION("_thisTransaction"); private final String value; LandedCostSource(String v) { value = v; } public String value() { return value; } public static LandedCostSource fromValue(String v) { for (LandedCostSource c: LandedCostSource.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
28.310345
108
0.683922
df6b10e7b0f2335602489cf02678c212ef2c34e9
1,866
package net.gvsun.gswork.vo.courseInfo; import java.io.Serializable; /************************************************************************** * Description: 文档VO * * @author:lixueteng * @date:2018/2/6 0006 **************************************************************************/ public class DocumentVO implements Serializable{ private Integer id; private String resourceUrl; private String documentName; private String siteName; private String path; /** * 文件名 */ private String fileName; /** * 文件的url */ private String fileUrl; private String size; public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getFileName() { return fileName; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public DocumentVO setFileName(String fileName) { this.fileName = fileName; return this; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public String getFileUrl() { return fileUrl; } public DocumentVO setFileUrl(String fileUrl) { this.fileUrl = fileUrl; return this; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; } public String getDocumentName() { return documentName; } public void setDocumentName(String documentName) { this.documentName = documentName; } }
19.851064
76
0.555198
f83346272063c5a922cdb543a5c454f646747c11
1,038
package com.jianma.yxyp.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jianma.yxyp.dao.StageDao; import com.jianma.yxyp.model.Stage; import com.jianma.yxyp.service.StageService; @Service @Component @Qualifier(value = "stageServiceImpl") @Transactional public class StageServiceImpl implements StageService { @Autowired @Qualifier(value = "stageDaoImpl") private StageDao stageDaoImpl; @Override public void createStage(Stage stage) { stageDaoImpl.createStage(stage); } @Override public void updateStage(Stage stage) { stageDaoImpl.updateStage(stage); } @Override public void deleteStage(int id) { stageDaoImpl.deleteStage(id); } @Override public List<Stage> getAllStage() { return stageDaoImpl.getAllStage(); } }
22.085106
64
0.793834
769c56eb6b995a4b5f56802425a85eb13334b138
6,723
/* * Copyright 2008 Marc Boorshtein * * 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 net.sourceforge.myvd.inserts.mapping; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPAttributeSet; import com.novell.ldap.LDAPConstraints; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPModification; import com.novell.ldap.LDAPSearchConstraints; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import net.sourceforge.myvd.chain.AddInterceptorChain; import net.sourceforge.myvd.chain.BindInterceptorChain; import net.sourceforge.myvd.chain.CompareInterceptorChain; import net.sourceforge.myvd.chain.DeleteInterceptorChain; import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain; import net.sourceforge.myvd.chain.ModifyInterceptorChain; import net.sourceforge.myvd.chain.PostSearchCompleteInterceptorChain; import net.sourceforge.myvd.chain.PostSearchEntryInterceptorChain; import net.sourceforge.myvd.chain.RenameInterceptorChain; import net.sourceforge.myvd.chain.SearchInterceptorChain; import net.sourceforge.myvd.core.NameSpace; import net.sourceforge.myvd.inserts.Insert; import net.sourceforge.myvd.types.Attribute; import net.sourceforge.myvd.types.Bool; import net.sourceforge.myvd.types.DistinguishedName; import net.sourceforge.myvd.types.Entry; import net.sourceforge.myvd.types.ExtendedOperation; import net.sourceforge.myvd.types.Filter; import net.sourceforge.myvd.types.Int; import net.sourceforge.myvd.types.Password; import net.sourceforge.myvd.types.Results; import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPAttributeSet; import com.novell.ldap.LDAPConstraints; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPModification; import com.novell.ldap.LDAPSearchConstraints; public class AttributeCleaner implements Insert { public static final Attribute ALL_ATTRIBS = new Attribute("*"); String key; String name; boolean clearAttributes; public void configure(String name, Properties props, NameSpace nameSpace) throws LDAPException { this.name = name; if (nameSpace == null) { key = "ATTRIB_CLEANER." + name; } else { key = "ATTRIB_CLEANER." + nameSpace.getLabel() + "." + name; } this.clearAttributes = props.getProperty("clearAttributes", "false").equalsIgnoreCase("true"); } public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { chain.nextAdd(entry,constraints); } public void bind(BindInterceptorChain chain, DistinguishedName dn, Password pwd, LDAPConstraints constraints) throws LDAPException { chain.nextBind(dn,pwd,constraints); } public void compare(CompareInterceptorChain chain, DistinguishedName dn, Attribute attrib, LDAPConstraints constraints) throws LDAPException { chain.nextCompare(dn,attrib,constraints); } public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { chain.nextDelete(dn,constraints); } public void extendedOperation(ExetendedOperationInterceptorChain chain, ExtendedOperation op, LDAPConstraints constraints) throws LDAPException { chain.nextExtendedOperations(op,constraints); } public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { chain.nextModify(dn,mods,constraints); } public void search(SearchInterceptorChain chain, DistinguishedName base, Int scope, Filter filter, ArrayList<Attribute> attributes, Bool typesOnly, Results results, LDAPSearchConstraints constraints) throws LDAPException { ArrayList<Attribute> origAttribs = new ArrayList<Attribute>(); Iterator<Attribute> it = attributes.iterator(); while (it.hasNext()) { origAttribs.add(new Attribute(it.next().getAttribute().getName())); } chain.getRequest().put(key,origAttribs); if (this.clearAttributes) { attributes = new ArrayList<Attribute>(); } chain.nextSearch(base,scope,filter,attributes,typesOnly,results,constraints); } public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, Bool deleteOldRdn, LDAPConstraints constraints) throws LDAPException { chain.nextRename(dn,newRdn,deleteOldRdn,constraints); } public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, DistinguishedName newParentDN, Bool deleteOldRdn, LDAPConstraints constraints) throws LDAPException { chain.nextRename(dn,newRdn,newParentDN,deleteOldRdn,constraints); } public void postSearchEntry(PostSearchEntryInterceptorChain chain, Entry entry, DistinguishedName base, Int scope, Filter filter, ArrayList<Attribute> attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { chain.nextPostSearchEntry(entry,base,scope,filter,attributes,typesOnly,constraints); ArrayList<Attribute> origAttributes = (ArrayList<Attribute>) chain.getRequest().get(key); attributes.clear(); attributes.addAll(origAttributes); if (attributes.size() != 0 && ! attributes.contains(ALL_ATTRIBS)) { LDAPAttributeSet newAttribs = new LDAPAttributeSet(); Iterator<Attribute> it = attributes.iterator(); while (it.hasNext()) { LDAPAttribute attrib = entry.getEntry().getAttribute(it.next().getAttribute().getName()); if (attrib != null) { newAttribs.add(attrib); } } entry.setEntry(new LDAPEntry(entry.getEntry().getDN(),newAttribs)); } } public void postSearchComplete(PostSearchCompleteInterceptorChain chain, DistinguishedName base, Int scope, Filter filter, ArrayList<Attribute> attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { chain.nextPostSearchComplete(base,scope,filter,attributes,typesOnly,constraints); } public String getName() { return this.name; } public void shutdown() { // TODO Auto-generated method stub } }
32.478261
96
0.784025
8e3206dc5f861e2171f938dc00db96c842d1da92
2,954
/* * Copyright 2014-16 Skynav, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY SKYNAV, INC. AND ITS CONTRIBUTORS “AS IS” AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.skynav.ttpe.geometry; import java.text.MessageFormat; import java.util.Locale; public class Rectangle { public static final Rectangle EMPTY = new Rectangle(); private Point origin; private Extent extent; public Rectangle() { this(Point.ZERO, Extent.EMPTY); } public Rectangle(double x, double y, double w, double h) { this(new Point(x, y), new Extent(w, h)); } public Rectangle(Point origin, Extent extent) { assert origin != null; this.origin = new Point(origin); assert extent != null; this.extent = new Extent(extent); } public double getX() { return origin.getX(); } public double getY() { return origin.getY(); } public double getWidth() { return extent.getWidth(); } public double getHeight() { return extent.getHeight(); } public Point getOrigin() { return origin; } public Extent getExtent() { return extent; } public boolean isEmpty() { return (getWidth() == 0) || (getHeight() == 0); } public java.awt.geom.Rectangle2D getAWTRectangle() { return new java.awt.geom.Rectangle2D.Double(getX(), getY(), getWidth(), getHeight()); } private static final MessageFormat rectangleFormatter = new MessageFormat("[{0,number,#.####},{1,number,#.####},{2,number,#.####},{3,number,#.####}]", Locale.US); @Override public String toString() { return rectangleFormatter.format(new Object[] {getX(), getY(), getWidth(), getHeight()}); } }
31.763441
114
0.675355
ed5bf162fa212bf378fdd1c816fded006245d8e0
12,134
package com.xiaoaiai.PagesBeans.AccostBeans; import com.lazy.annotations.Android; import com.lazy.annotations.Description; import com.lazy.bean.BaseBean; import com.lazy.controls.ImageView; import com.lazy.controls.TextView; import macaca.client.MacacaClient; public class ChartBean extends BaseBean { @Android(xpath="//android.widget.FrameLayout/android.view.View[1]") @Description(description="") public ImageView view1; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/txt_title']") @Description(description="搭讪") public TextView textView1; @Android(xpath="//android.view.View[@resource-id='com.zkj.guimi:id/blank']") @Description(description="") public ImageView view2; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']") @Description(description="") public ImageView listView3; @Android(xpath="//android.widget.ProgressBar[@resource-id='com.zkj.guimi:id/dh_circle_bar']") @Description(description="") public ImageView dd; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/dh_animation_img']") @Description(description="") public ImageView imageView5; @Android(xpath="//android.support.v4.view.ViewPager[@resource-id='com.zkj.guimi:id/adv_viewpager']") @Description(description="") public ImageView viewPager6; @Android(xpath="//android.support.v4.view.ViewPager[@resource-id='com.zkj.guimi:id/adv_viewpager']/android.widget.ImageView[1]") @Description(description="") public ImageView banner; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.view.View[1]") @Description(description="") public ImageView view8; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/title' and @text='魅力榜']") @Description(description="魅力榜") public TextView charmChartTable; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]") @Description(description="查看全部") public TextView lookCharmButton; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.ImageView[1]") @Description(description="") public ImageView imageView9; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[2]/android.view.View[1]") @Description(description="") public ImageView view10; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[2]/android.widget.RelativeLayout[1]/android.view.View[1]") @Description(description="") public ImageView view11; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/title' and @text='魅力总榜']") @Description(description="魅力总榜") public TextView charmAlltabl; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[2]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]") @Description(description="查看全部") public TextView lookCharmAllButton; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[2]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.widget.ImageView[1]") @Description(description="") public ImageView imageView12; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[3]/android.widget.ImageView[1]") @Description(description="") public ImageView imageView13; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[3]/android.widget.ImageView[2]") @Description(description="") public ImageView imageView14; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/name' and @text='让人阿爸']") @Description(description="让人阿爸") public TextView textView6; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/level' and @text='10']") @Description(description="10") public TextView textView7; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[3]/android.widget.ImageView[3]") @Description(description="") public ImageView imageView15; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[3]/android.widget.ImageView[4]") @Description(description="") public ImageView imageView16; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/value1' and @text='705152']") @Description(description="705152") public TextView textView8; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/rank' and @text='1']") @Description(description="1") public TextView textView9; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[3]/android.view.View[1]") @Description(description="") public ImageView view17; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[4]/android.widget.ImageView[1]") @Description(description="") public ImageView imageView18; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[4]/android.widget.ImageView[2]") @Description(description="") public ImageView imageView19; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/name' and @text='asd2']") @Description(description="asd2") public TextView textView10; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/level' and @text='4']") @Description(description="4") public TextView textView11; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[4]/android.widget.ImageView[3]") @Description(description="") public ImageView imageView20; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[4]/android.widget.ImageView[4]") @Description(description="") public ImageView imageView21; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/value1' and @text='658060']") @Description(description="658060") public TextView textView12; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/rank' and @text='2']") @Description(description="2") public TextView textView13; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[4]/android.view.View[1]") @Description(description="") public ImageView view22; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[5]/android.widget.ImageView[1]") @Description(description="") public ImageView imageView23; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[5]/android.widget.ImageView[2]") @Description(description="") public ImageView imageView24; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/name' and @text='美人']") @Description(description="美人") public TextView textView14; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/level' and @text='12']") @Description(description="12") public TextView textView15; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[5]/android.widget.ImageView[3]") @Description(description="") public ImageView imageView25; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.RelativeLayout[5]/android.widget.ImageView[4]") @Description(description="") public ImageView imageView26; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/value1' and @text='129790']") @Description(description="129790") public TextView textView16; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/rank' and @text='3']") @Description(description="3") public TextView textView17; @Android(xpath="//android.widget.ListView[@resource-id='com.zkj.guimi:id/scroll']/android.widget.LinearLayout[3]/android.view.View[1]") @Description(description="") public ImageView view27; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/fa_id_photo']") @Description(description="ID照") public TextView textView18; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/fc_tv_group']") @Description(description="心情") public TextView textView19; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/fm_tv_top_list']") @Description(description="榜单") public TextView textView20; @Android(xpath="//android.widget.RelativeLayout[@resource-id='com.zkj.guimi:id/tab_0']/android.view.View[1]") @Description(description="") public ImageView view28; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/image_0']") @Description(description="") public ImageView imageView29; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/text_0']") @Description(description="搭讪") public TextView textView21; @Android(xpath="//android.widget.RelativeLayout[@resource-id='com.zkj.guimi:id/tab_1']/android.view.View[1]") @Description(description="") public ImageView view30; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/image_1']") @Description(description="") public ImageView imageView31; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/text_1']") @Description(description="发现") public TextView textView22; @Android(xpath="//android.widget.RelativeLayout[@resource-id='com.zkj.guimi:id/tab_2']/android.view.View[1]") @Description(description="") public ImageView view32; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/image_2']") @Description(description="") public ImageView imageView33; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/text_2']") @Description(description="消息") public TextView textView23; @Android(xpath="//android.widget.RelativeLayout[@resource-id='com.zkj.guimi:id/tab_3']/android.view.View[1]") @Description(description="") public ImageView view34; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/image_3']") @Description(description="") public ImageView imageView35; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/text_3']") @Description(description="约跳") public TextView textView24; @Android(xpath="//android.widget.RelativeLayout[@resource-id='com.zkj.guimi:id/tab_4']/android.view.View[1]") @Description(description="") public ImageView view36; @Android(xpath="//android.widget.ImageView[@resource-id='com.zkj.guimi:id/image_4']") @Description(description="") public ImageView imageView37; @Android(xpath="//android.widget.TextView[@resource-id='com.zkj.guimi:id/text_4']") @Description(description="我") public TextView textView25; public ChartBean(MacacaClient aDriver){super(aDriver);} }
36.881459
210
0.718477
4de21efb3ce7a6f36f8fe8fdd92608280088f898
4,742
/* * 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.aliyuncs.sofa.transform.v20190815; import com.aliyuncs.sofa.model.v20190815.GetLinkeBahamutPipelinegetcomponentresultResponse; import com.aliyuncs.sofa.model.v20190815.GetLinkeBahamutPipelinegetcomponentresultResponse.Result; import com.aliyuncs.transform.UnmarshallerContext; public class GetLinkeBahamutPipelinegetcomponentresultResponseUnmarshaller { public static GetLinkeBahamutPipelinegetcomponentresultResponse unmarshall(GetLinkeBahamutPipelinegetcomponentresultResponse getLinkeBahamutPipelinegetcomponentresultResponse, UnmarshallerContext _ctx) { getLinkeBahamutPipelinegetcomponentresultResponse.setRequestId(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.RequestId")); getLinkeBahamutPipelinegetcomponentresultResponse.setResultCode(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.ResultCode")); getLinkeBahamutPipelinegetcomponentresultResponse.setResultMessage(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.ResultMessage")); getLinkeBahamutPipelinegetcomponentresultResponse.setErrorMessage(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.ErrorMessage")); getLinkeBahamutPipelinegetcomponentresultResponse.setErrorMsgParamsMap(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.ErrorMsgParamsMap")); getLinkeBahamutPipelinegetcomponentresultResponse.setMessage(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Message")); getLinkeBahamutPipelinegetcomponentresultResponse.setResponseStatusCode(_ctx.longValue("GetLinkeBahamutPipelinegetcomponentresultResponse.ResponseStatusCode")); getLinkeBahamutPipelinegetcomponentresultResponse.setSuccess(_ctx.booleanValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Success")); Result result = new Result(); result.setCausedBy(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.CausedBy")); result.setComponentDisplayName(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ComponentDisplayName")); result.setComponentId(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ComponentId")); result.setComponentName(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ComponentName")); result.setComponentType(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ComponentType")); result.setData(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.Data")); result.setDetailStatus(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.DetailStatus")); result.setErrorMsg(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ErrorMsg")); result.setExecutionResult(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ExecutionResult")); result.setExecutionTaskId(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ExecutionTaskId")); result.setExpressionData(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ExpressionData")); result.setExpressionDesc(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ExpressionDesc")); result.setExpressionRule(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.ExpressionRule")); result.setFailReason(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.FailReason")); result.setHtmlText(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.HtmlText")); result.setLoggerUrl(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.LoggerUrl")); result.setStatus(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.Status")); result.setSuccess(_ctx.booleanValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.Success")); result.setTipHtml(_ctx.stringValue("GetLinkeBahamutPipelinegetcomponentresultResponse.Result.TipHtml")); getLinkeBahamutPipelinegetcomponentresultResponse.setResult(result); return getLinkeBahamutPipelinegetcomponentresultResponse; } }
80.372881
204
0.866723
85861507f09bb2a3190aef6fe4d31921366273f6
1,305
package cloud.lemonslice.afterthedrizzle.helper; public final class ColorHelper { public static int getRed(int color) { return color >> 16 & 255; } public static int getGreen(int color) { return color >> 8 & 255; } public static int getBlue(int color) { return color & 255; } public static int getAlpha(int color) { return color >> 24 & 255; } public static float getRedF(int color) { return getRed(color) / 255.0F; } public static float getGreenF(int color) { return getGreen(color) / 255.0F; } public static float getBlueF(int color) { return getBlue(color) / 255.0F; } public static float getAlphaF(int color) { return getAlpha(color) / 255.0F; } public static int simplyMixColor(int color1, float alpha1, int color2, float alpha2) { int red = (int) (getRed(color1) * alpha1 + getRed(color2) * alpha2); int green = (int) (getGreen(color1) * alpha1 + getGreen(color2) * alpha2); int blue = (int) (getBlue(color1) * alpha1 + getBlue(color2) * alpha2); int alpha = (int) (getAlpha(color1) * alpha1 + getAlpha(color2) * alpha2); return alpha << 24 | red << 16 | green << 8 | blue; } }
24.166667
88
0.590038
3d58c335ccef6f2cf2de1fdf8726b11b56d8001f
2,258
package org.hswebframework.web.organizational.authorization.simple; import com.alibaba.fastjson.JSON; import org.hswebframework.web.bean.BeanFactory; import org.hswebframework.web.bean.FastBeanCopier; import org.hswebframework.web.organizational.authorization.*; import org.hswebframework.web.organizational.authorization.relation.Relation; import org.hswebframework.web.organizational.authorization.relation.Relations; import org.hswebframework.web.organizational.authorization.relation.SimpleRelation; import org.hswebframework.web.organizational.authorization.relation.SimpleRelations; import java.util.Map; public class SimplePersonnelAuthorizationBuilder { private static FastBeanCopier.DefaultConverter converter = new FastBeanCopier.DefaultConverter(); static { converter.setBeanFactory(new BeanFactory() { @Override @SuppressWarnings("all") public <T> T newInstance(Class<T> targetClass) { if (targetClass == Position.class) { return (T) new SimplePosition(); } if (targetClass == Personnel.class) { return (T) new SimplePersonnel(); } if (targetClass == Department.class) { return (T) new SimpleDepartment(); } if (targetClass == Organization.class) { return (T) new SimpleOrganization(); } if (targetClass == District.class) { return (T) new SimpleDistrict(); } if (targetClass == Relation.class) { return (T) new SimpleRelation(); } if (targetClass == Relations.class) { return (T) new SimpleRelations(); } return FastBeanCopier.getBeanFactory().newInstance(targetClass); } }); } public static SimplePersonnelAuthentication fromJson(String json) { return fromMap(JSON.parseObject(json)); } public static SimplePersonnelAuthentication fromMap(Map<String,Object> map) { return FastBeanCopier.copy(map, new SimplePersonnelAuthentication(), converter); } }
39.614035
100
0.627547
1a749536cb57fe7b8e2e71e95772d05c391f4f7a
8,628
// ConfigurationList.java -- // // ConfigurationList.java is part of ElectricCommander. // // Copyright (c) 2005-2012 Electric Cloud, Inc. // All rights reserved. // package ecplugins.xen.client; import java.util.HashMap; import java.util.Map; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.electriccloud.commander.client.ChainedCallback; import com.electriccloud.commander.client.requests.RunProcedureRequest; import com.electriccloud.commander.client.responses.DefaultRunProcedureResponseCallback; import com.electriccloud.commander.client.responses.RunProcedureResponse; import com.electriccloud.commander.gwt.client.requests.CgiRequestProxy; import com.electriccloud.commander.gwt.client.ui.ListTable; import com.electriccloud.commander.gwt.client.ui.SimpleErrorBox; import com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder; import ecinternal.client.DialogClickHandler; import ecinternal.client.ListBase; import ecinternal.client.Loader; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createPageUrl; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createRedirectUrl; import static ecinternal.client.InternalComponentBaseFactory.getPluginName; /** * EC-Xen Configuration List. */ public class ConfigurationList extends ListBase { //~ Instance fields -------------------------------------------------------- private final XenConfigList m_configList; //~ Constructors ----------------------------------------------------------- public ConfigurationList() { //noinspection HardCodedStringLiteral super("ecgc", "Xen Configurations", "All Configurations"); m_configList = new XenConfigList(); } //~ Methods ---------------------------------------------------------------- @Override protected Anchor constructCreateLink() { CommanderUrlBuilder urlBuilder = createPageUrl(getPluginName(), "newConfiguration"); urlBuilder.setParameter("redirectTo", createRedirectUrl().buildString()); //noinspection HardCodedStringLiteral return new Anchor("Create Configuration", urlBuilder.buildString()); } @Override protected void load() { //noinspection HardCodedStringLiteral setStatus("Loading..."); Loader loader = new XenConfigListLoader(m_configList, this, new ChainedCallback() { @Override public void onComplete() { loadList(); } }); loader.load(); } private void deleteConfiguration(String configName) { //noinspection HardCodedStringLiteral setStatus("Deleting..."); clearErrorMessages(); // Build runProcedure request RunProcedureRequest request = getRequestFactory() .createRunProcedureRequest(); request.setProjectName("/plugins/EC-Xen/project"); request.setProcedureName("DeleteConfiguration"); request.addActualParameter("config", configName); request.setCallback(new DefaultRunProcedureResponseCallback(this) { @Override public void handleResponse( RunProcedureResponse response) { if (getLog().isDebugEnabled()) { getLog().debug( "Commander runProcedure request returned job id: " + response.getJobId()); } waitForJob(response.getJobId().toString()); } }); // Launch the procedure if (getLog().isDebugEnabled()) { getLog().debug("Issuing Commander request: " + request); } doRequest(request); } private void loadList() { ListTable listTable = getListTable(); if (!m_configList.isEmpty()) { //noinspection HardCodedStringLiteral listTable.addHeaderRow(true, "Configuration Name", "Server"); } for (String configName : m_configList.getConfigNames()) { // Config name Label configNameLabel = new Label(configName); // Server name String configServer = m_configList.getConfigServer(configName); Label configServerLabel = new Label(configServer); // "Edit" link CommanderUrlBuilder urlBuilder = createPageUrl(getPluginName(), "editConfiguration"); urlBuilder.setParameter("configName", configName); urlBuilder.setParameter("redirectTo", createRedirectUrl().buildString()); Anchor editConfigLink = new Anchor("Edit", urlBuilder.buildString()); // "Delete" link Anchor deleteConfigLink = new Anchor("Delete"); ClickHandler dch = new DialogClickHandler( new DeleteConfirmationDialog(configName, "Are you sure you want to delete the Xen configuration '" + configName + "'?") { @Override protected void doDelete() { deleteConfiguration(m_objectId); } }); deleteConfigLink.addClickHandler(dch); // Add the row Widget actions = this.getUIFactory() .constructActionList(editConfigLink, deleteConfigLink); listTable.addRow(configNameLabel, configServerLabel, actions); } clearStatus(); } private void waitForJob(final String jobId) { CgiRequestProxy cgiRequestProxy = new CgiRequestProxy( getPluginName(), "xenMonitor.cgi"); Map<String, String> cgiParams = new HashMap<String, String>(); cgiParams.put("jobId", jobId); // Pass debug flag to CGI, which will use it to determine whether to // clean up a successful job if ("1".equals(getGetParameter("debug"))) { cgiParams.put("debug", "1"); } try { cgiRequestProxy.issueGetRequest(cgiParams, new RequestCallback() { @Override public void onError( Request request, Throwable exception) { addErrorMessage("CGI request failed:: ", exception); } @Override public void onResponseReceived( Request request, Response response) { String responseString = response.getText(); if (getLog().isDebugEnabled()) { getLog().debug( "CGI response received: " + responseString); } if (responseString.startsWith("Success")) { // We're done! Location.reload(); } else { SimpleErrorBox error = getUIFactory() .createSimpleErrorBox( "Error occurred during configuration deletion: " + responseString); CommanderUrlBuilder urlBuilder = CommanderUrlBuilder .createUrl("jobDetails.php") .setParameter("jobId", jobId); error.add( new Anchor("(See job for details)", urlBuilder.buildString())); addErrorMessage(error); } } }); } catch (RequestException e) { addErrorMessage("CGI request failed:: ", e); } } }
35.506173
96
0.551808
f8de7ac38bb8f29a5aa32667d366c9c704482821
587
package com.stevesun.solutions; /** Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]*/ public class _280 { public void wiggleSort(int[] nums) { for(int i = 1; i < nums.length; i++){ if((i%2 == 0 && nums[i] > nums[i-1]) || (i%2 == 1 && nums[i] < nums[i-1])) swap(nums, i); } } void swap(int[] nums, int i){ int temp = nums[i-1]; nums[i-1] = nums[i]; nums[i] = temp; } }
32.611111
108
0.507666
b627bda5e6c157845a65bbdee52e26a0217eb3d5
613
package ru.job4j.ioc; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by gavrikov.a on 31/08/2017. */ public class ImportUserTest { @Test public void whenUserAddInStructureThenStructureHasSameUser() { ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); ImportUser importUser = context.getBean(ImportUser.class); User user = context.getBean(User.class); user.setName("ss"); importUser.addUser(user); } }
30.65
94
0.738989
38df0a24a753a20a00ec898df32077458ddaf598
3,479
/* * Copyright 2021, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.chatbot.server.google.chat; import io.spine.chatbot.google.chat.Space; import io.spine.chatbot.google.chat.SpaceHeader; import io.spine.chatbot.google.chat.SpaceId; import io.spine.chatbot.google.chat.command.RegisterSpace; import io.spine.chatbot.google.chat.event.SpaceRegistered; import io.spine.chatbot.google.chat.incoming.event.BotAddedToSpace; import io.spine.logging.Logging; import io.spine.server.aggregate.Aggregate; import io.spine.server.aggregate.Apply; import io.spine.server.command.Assign; import io.spine.server.event.React; /** * A room or direct message chat in the Google Chat. * * <p>Whenever the ChatBot is added to the space, the space is registered in the context. */ final class SpaceAggregate extends Aggregate<SpaceId, Space, Space.Builder> implements Logging { /** * Registers a new space when the ChatBot is added to the space. */ @React SpaceRegistered on(BotAddedToSpace e) { var space = e.getEvent() .getSpace(); var displayName = space.getDisplayName(); var spaceId = e.getSpace(); _info().log("Registering the space `%s` (`%s`) because the bot is added the space.", displayName, spaceId.getValue()); var header = SpaceHeader .newBuilder() .setDisplayName(displayName) .setThreaded(space.isThreaded()) .vBuild(); return SpaceRegistered .newBuilder() .setSpace(spaceId) .setHeader(header) .vBuild(); } /** * Registers the space in the context. */ @Assign SpaceRegistered handle(RegisterSpace c) { var header = c.getHeader(); var space = c.getId(); _info().log("Registering the space `%s` (`%s`) on direct registration request.", header.getDisplayName(), space.getValue()); var result = SpaceRegistered .newBuilder() .setSpace(space) .setHeader(header) .vBuild(); return result; } @Apply private void on(SpaceRegistered e) { builder().setHeader(e.getHeader()); } }
37.408602
96
0.669158
5070587f0ba1187a4295fe2964dffa1ec44d4b39
317
package com.a6raywa1cher.imageprocessingspring.util; import javafx.scene.canvas.Canvas; public class ResizableCanvas extends Canvas { @Override public boolean isResizable() { return true; } @Override public void resize(double width, double height) { this.setWidth(width); this.setHeight(height); } }
16.684211
52
0.757098
39890248209efbf12bbb55294c0ae864f6505e6f
143
package com.neandroid.preferences; public interface PreferencesConfig { String SHARED_PREFS_NAME = "com.android.calendar_preferences"; }
20.428571
66
0.804196
15b2ff77b26764d6023cdcfd6bd47682a7a36ed2
856
package state.action.movement; import state.agent.AgentUtils; import state.agent.IAgent; /** * Allows an agent to move straight to a specified target agent. * @author Jorge Raad * @author David Miron */ public class MoveStraightToAgent extends MovementAction { IAgent baseAgent; public MoveStraightToAgent(IAgent baseAgent) { this.baseAgent = baseAgent; } /** * Move the baseAgent to the target agent in a straight line. * @param agent The agent to move to. */ @Override public void execute(IAgent agent) { double speed = Math.sqrt(Math.pow(baseAgent.getXVelocity(), 2) + Math.pow(baseAgent.getYVelocity(), 2)); double absoluteAngle = AgentUtils.getAngleBetween(baseAgent, agent); baseAgent.updateVelocity(speed*Math.cos(absoluteAngle), speed*Math.sin(absoluteAngle)); } }
29.517241
112
0.700935
7683ab8108a82dab383179675232c6f61e578ab7
1,993
/* * Copyright 2015 herd contributors * * 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.finra.dm.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.amazonaws.services.kms.model.InvalidCiphertextException; import org.junit.Test; import org.finra.dm.dao.impl.MockKmsOperationsImpl; import org.finra.dm.model.dto.AwsParamsDto; /** * This class tests the functionality of KmsDao. */ public class KmsDaoTest extends AbstractDaoTest { @Test public void testDecrypt() { // Decrypt the test ciphertext. AwsParamsDto testAwsParamsDto = new AwsParamsDto(); testAwsParamsDto.setHttpProxyHost(HTTP_PROXY_HOST); testAwsParamsDto.setHttpProxyPort(HTTP_PROXY_PORT); // Decrypt the test ciphertext. String resultPlainText = kmsDao.decrypt(testAwsParamsDto, MockKmsOperationsImpl.MOCK_CIPHER_TEXT); // Validate the results. assertEquals(MockKmsOperationsImpl.MOCK_PLAIN_TEXT, resultPlainText); } @Test public void testDecryptInvalidCipher() { try { // Try to decrypt an invalid ciphertext. kmsDao.decrypt(new AwsParamsDto(), MockKmsOperationsImpl.MOCK_CIPHER_TEXT_INVALID); fail("Suppose to throw an InvalidCiphertextException when cipher text is invalid."); } catch (Exception e) { assertEquals(InvalidCiphertextException.class, e.getClass()); } } }
32.145161
106
0.718013
c1c3b08ac92e0ef9930b4b667713c6524489abdc
12,647
/* * Copyright (C) 2016-2020 Marco Collovati ([email protected]) * * 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.vaadin.addon.twitter; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.dependency.JsModule; /** * Embed multiple Tweets in a compact, single-column view. * * Display the latest Tweets from a single Twitter account, multiple accounts, or tap into the worldwide * conversation around a topic grouped in a search result. * * A Twitter collection may be rendered in either a list or a responsive grid template. * * Documentation is taken from <a href="https://dev.twitter.com/web/overview">Twitter for Websites</a>. */ @Tag("tws-timeline") @JsModule("./src/tws-timeline.js") public final class Timeline extends AbstractWidget<Timeline> { private Timeline(Datasource datasource, String primaryArgument) { getElement().setProperty("datasource", datasource.toString()); setPrimaryArgument(Objects.requireNonNull(primaryArgument)); if (primaryArgument.trim().isEmpty()) { throw new IllegalArgumentException("primary argument must no be empty or blank"); } } /** * Creates a timeline with Tweets from an individual user identified * by {@code screenName}. * * @param screenName a valid Twitter username * @return a timeline instance */ public static Timeline profile(String screenName) { return new Timeline(Datasource.profile, screenName); } /** * Creates a timeline with an individual Twitter user's likes. * * @param screenName a valid Twitter username * @return a timeline instance */ public static Timeline likes(String screenName) { return new Timeline(Datasource.likes, screenName); } /** * Creates a timeline with Tweets from a collection. * * @param collectionId a valid Twitter collection id * @return a timeline instance */ public static Timeline collection(String collectionId) { return new Timeline(Datasource.collection, collectionId); } /** * Creates a timeline with Twitter content that you have the URL for. * * Supported content includes profiles, likes, lists, and collections. * * @param url The permalink to one of a profile, likes timeline, list, or collection * @return a timeline instance */ public static Timeline url(String url) { try { return url(new URL(Objects.requireNonNull(url))); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid url: " + url, e); } } /** * Creates a timeline with Twitter content that you have the URL for. * * Supported content includes profiles, likes, lists, and collections. * * @param url The permalink to one of a profile, likes timeline, list, or collection * @return a timeline instance */ public static Timeline url(URL url) { try { return new Timeline(Datasource.url, url.toURI().toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid url: " + url, e); } } /** * Creates a timeline with a timeline widget configuration. * * @param widgetId A valid Twitter widget id * @return a timeline instance */ public static Timeline widget(String widgetId) { return new Timeline(Datasource.widget, widgetId); } /** * Creates a timeline with a Twitter list. * * @param screenName A valid Twitter screen name * @param slug The string identifier for a list * @return a timeline instance */ public static Timeline list(String screenName, String slug) { if (Objects.requireNonNull(screenName).trim().isEmpty()) { throw new IllegalArgumentException("screenName must no be empty or blank"); } if (Objects.requireNonNull(slug).trim().isEmpty()) { throw new IllegalArgumentException("slug must no be empty or blank"); } return new Timeline(Datasource.list, String.format("%s@%s", slug, screenName)); } /** * Creates a timeline with a Twitter list. * * @param listId A valid Twitter list id * @return a timeline instance */ public static Timeline list(String listId) { return new Timeline(Datasource.list, listId); } /** * Returns the datasource primary argument. * * Depending on {@link Datasource} type could be a screen name, a collection id, * an url, a widget id or a combination of screenName and slug (slugId@screenName). * * @return the datasource primary argument as string. */ public String getDatasourcePrimaryArgument() { return internalGetPrimaryArgument(); } /** * Returns the datasource type of this timeline. * * @return the datasource type of this timeline */ public Datasource getDatasource() { return Datasource.valueOf(getElement().getProperty("datasource")); } /** * Apply the specified aria-polite behavior to the rendered timeline. * * @param ariaPolite aria-polite behavior. * @return the object itself for further configuration */ public Timeline withAriaPolite(AriaPolite ariaPolite) { getElement().setProperty("ariaPolite", ariaPolite.toString()); return this; } /** * Returns the aria-polite behavior. * * @return the aria-polite behavior */ public AriaPolite getAriaPolite() { return AriaPolite.valueOf(getElement().getProperty("ariaPolite")); } /** * Adjust the color of borders inside the widget. * * @param borderColor Hexadecimal color value. * @return the object itself for further configuration */ public Timeline withBorderColor(String borderColor) { getElement().getProperty("borderColor", borderColor); return this; } /** * Returns the color of borders. * * @return color value */ public String getBorderColor() { return getElement().getProperty("borderColor"); } /** * Set the chrome components that defines the display of design elements in the widget. * * @param chrome chrome components * @return the object itself for further configuration */ public Timeline withChrome(Chrome... chrome) { if (chrome.length == 0) { throw new IllegalArgumentException("At least one chrome component is required"); } setStringList("chrome", chromeToString(chrome).stream()); return this; } /** * Removes chrome components from the current configuration. * * @param chrome chrome components to remove * @return the object itself for further configuration */ public Timeline withoutChrome(Chrome... chrome) { if (chrome.length == 0) { clearStringList("chrome"); } else { removeFromStringList("chrome", chromeToString(chrome).toArray(new String[chrome.length])); } return this; } /** * Adds chrome components to the the current configuration. * * @param chrome chrome components to add * @return the object itself for further configuration */ public Timeline addChrome(Chrome... chrome) { if (chrome.length == 0) { throw new IllegalArgumentException("At least one chrome component is required"); } List<String> actual = getStringList("chrome"); actual.addAll(chromeToString(chrome)); setStringList("chrome", actual.stream()); return this; } /** * Returns the chrome components applied to the widget. * * @return a list of chrome components */ public Set<Chrome> getChrome() { LinkedHashSet<Chrome> actual = getStringList("chrome") .stream().map(Chrome::valueOf) .collect(Collectors.toCollection(LinkedHashSet::new)); return Collections.unmodifiableSet(actual); } /** * Sets the number of Tweets that must be displayed. * * {@code tweetLimit} must be between 1 and 20. * * Note that the height of the widget will be calculated based on specified tweetLimit * * @param tweetLimit number of Tweets that must be displayed * @return the object itself for further configuration * @throws IllegalArgumentException if {@code tweetLimit} is less than 1 or greater than 20 */ public Timeline withTweetLimit(int tweetLimit) { if (tweetLimit < 1 || tweetLimit > 20) { throw new IllegalArgumentException("Tweet limit must be between 1 and 20"); } getElement().setProperty("tweetLimit", tweetLimit); return this; } /** * Returns the number of tweets that must be displayed. * * @return the number of tweets that must be displayed */ public int getTweetLimit() { return getElement().getProperty("tweetLimit", 0); } private Set<String> chromeToString(Chrome[] chrome) { return Stream.of(chrome).map(Chrome::name).collect(Collectors.toCollection(LinkedHashSet::new)); } /** * The data source definition describes what content will hydrate the embedded timeline. */ public enum Datasource { /** * Tweets from an individual user. * * Primary argument must be a valid screen name. */ profile, /** * Individual Twitter user's likes. * * Primary argument must be a valid screen name. */ likes, /** * Tweets from a collection. * * Primary argument must be a valid collection id. */ collection, /** * Twitter list. * * Primary argument must be a valid screen name combined * with a list id or slug (string identifier). */ list, /** * Twitter content identified by URL. * * Primary argument must be a permalink to one of a profile, * likes timeline, list, or collection. */ url, /** * Use a timeline widget configuration. * * Primary argument must be a valid widget id. */ widget } /** * Display of design elements in the widget. */ public enum Chrome { /** * Hides the timeline header. * * Implementing sites must add their own Twitter attribution, link to the source timeline, * and comply with other Twitter * <a href="https://about.twitter.com/company/display-requirements">display requirements</a>. */ noheader, /** * Hides the timeline footer and Tweet composer link, if included in the timeline widget type. */ nofooter, /** * Removes all borders within the widget including borders surrounding the widget area and separating Tweets. */ noborders, /** * Removes the widget's background color. */ transparent, /** * Crops and hides the main timeline scrollbar, if visible. * * Please consider that hiding standard user interface components can affect * the accessibility of your website. */ noscrollbar } /** * Aria-polite behavior. */ public enum AriaPolite { /** * Polite. */ polite, /** * Assertive. */ assertive, /** * Rude. */ rude } }
31.460199
117
0.626315
f7c1a85f4109b9f492c1b352e81888b5723e90aa
12,803
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.ec2.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Describes a disk image. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DiskImageDescription" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DiskImageDescription implements Serializable, Cloneable { /** * <p> * The checksum computed for the disk image. * </p> */ private String checksum; /** * <p> * The disk image format. * </p> */ private String format; /** * <p> * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for * an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST Requests</a> * topic in the <i>Amazon Simple Storage Service Developer Guide</i>. * </p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. * </p> */ private String importManifestUrl; /** * <p> * The size of the disk image, in GiB. * </p> */ private Long size; /** * <p> * The checksum computed for the disk image. * </p> * * @param checksum * The checksum computed for the disk image. */ public void setChecksum(String checksum) { this.checksum = checksum; } /** * <p> * The checksum computed for the disk image. * </p> * * @return The checksum computed for the disk image. */ public String getChecksum() { return this.checksum; } /** * <p> * The checksum computed for the disk image. * </p> * * @param checksum * The checksum computed for the disk image. * @return Returns a reference to this object so that method calls can be chained together. */ public DiskImageDescription withChecksum(String checksum) { setChecksum(checksum); return this; } /** * <p> * The disk image format. * </p> * * @param format * The disk image format. * @see DiskImageFormat */ public void setFormat(String format) { this.format = format; } /** * <p> * The disk image format. * </p> * * @return The disk image format. * @see DiskImageFormat */ public String getFormat() { return this.format; } /** * <p> * The disk image format. * </p> * * @param format * The disk image format. * @return Returns a reference to this object so that method calls can be chained together. * @see DiskImageFormat */ public DiskImageDescription withFormat(String format) { setFormat(format); return this; } /** * <p> * The disk image format. * </p> * * @param format * The disk image format. * @see DiskImageFormat */ public void setFormat(DiskImageFormat format) { withFormat(format); } /** * <p> * The disk image format. * </p> * * @param format * The disk image format. * @return Returns a reference to this object so that method calls can be chained together. * @see DiskImageFormat */ public DiskImageDescription withFormat(DiskImageFormat format) { this.format = format.toString(); return this; } /** * <p> * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for * an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST Requests</a> * topic in the <i>Amazon Simple Storage Service Developer Guide</i>. * </p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. * </p> * * @param importManifestUrl * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned * URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST * Requests</a> topic in the <i>Amazon Simple Storage Service Developer Guide</i>.</p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. */ public void setImportManifestUrl(String importManifestUrl) { this.importManifestUrl = importManifestUrl; } /** * <p> * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for * an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST Requests</a> * topic in the <i>Amazon Simple Storage Service Developer Guide</i>. * </p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. * </p> * * @return A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned * URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST * Requests</a> topic in the <i>Amazon Simple Storage Service Developer Guide</i>.</p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. */ public String getImportManifestUrl() { return this.importManifestUrl; } /** * <p> * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for * an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST Requests</a> * topic in the <i>Amazon Simple Storage Service Developer Guide</i>. * </p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. * </p> * * @param importManifestUrl * A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned * URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the <a * href="https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html">Authenticating REST * Requests</a> topic in the <i>Amazon Simple Storage Service Developer Guide</i>.</p> * <p> * For information about the import manifest referenced by this API action, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html">VM Import Manifest</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public DiskImageDescription withImportManifestUrl(String importManifestUrl) { setImportManifestUrl(importManifestUrl); return this; } /** * <p> * The size of the disk image, in GiB. * </p> * * @param size * The size of the disk image, in GiB. */ public void setSize(Long size) { this.size = size; } /** * <p> * The size of the disk image, in GiB. * </p> * * @return The size of the disk image, in GiB. */ public Long getSize() { return this.size; } /** * <p> * The size of the disk image, in GiB. * </p> * * @param size * The size of the disk image, in GiB. * @return Returns a reference to this object so that method calls can be chained together. */ public DiskImageDescription withSize(Long size) { setSize(size); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getChecksum() != null) sb.append("Checksum: ").append(getChecksum()).append(","); if (getFormat() != null) sb.append("Format: ").append(getFormat()).append(","); if (getImportManifestUrl() != null) sb.append("ImportManifestUrl: ").append(getImportManifestUrl()).append(","); if (getSize() != null) sb.append("Size: ").append(getSize()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DiskImageDescription == false) return false; DiskImageDescription other = (DiskImageDescription) obj; if (other.getChecksum() == null ^ this.getChecksum() == null) return false; if (other.getChecksum() != null && other.getChecksum().equals(this.getChecksum()) == false) return false; if (other.getFormat() == null ^ this.getFormat() == null) return false; if (other.getFormat() != null && other.getFormat().equals(this.getFormat()) == false) return false; if (other.getImportManifestUrl() == null ^ this.getImportManifestUrl() == null) return false; if (other.getImportManifestUrl() != null && other.getImportManifestUrl().equals(this.getImportManifestUrl()) == false) return false; if (other.getSize() == null ^ this.getSize() == null) return false; if (other.getSize() != null && other.getSize().equals(this.getSize()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getChecksum() == null) ? 0 : getChecksum().hashCode()); hashCode = prime * hashCode + ((getFormat() == null) ? 0 : getFormat().hashCode()); hashCode = prime * hashCode + ((getImportManifestUrl() == null) ? 0 : getImportManifestUrl().hashCode()); hashCode = prime * hashCode + ((getSize() == null) ? 0 : getSize().hashCode()); return hashCode; } @Override public DiskImageDescription clone() { try { return (DiskImageDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
34.790761
137
0.617902
d2886db198fe96bab51b0481e6cd7ac98ac60d7a
1,532
package it.sorint.welearnbe.repository.entity; import java.util.List; import java.util.UUID; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="projects") public class ProjectBE { private UUID id; private String name; private UUID previousProjectID; private int version; List<String> files; List<ExecutionConfigBE> executionConfigs; public ProjectBE(UUID id, String name, UUID previousProjectID, int version, List<String> files, List<ExecutionConfigBE> executionConfigs) { super(); this.id = id; this.name = name; this.previousProjectID = previousProjectID; this.version = version; this.files = files; this.executionConfigs = executionConfigs; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public UUID getPreviousProjectID() { return previousProjectID; } public void setPreviousProjectID(UUID previousProjectID) { this.previousProjectID = previousProjectID; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public List<String> getFiles() { return files; } public void setFiles(List<String> files) { this.files = files; } public List<ExecutionConfigBE> getExecutionConfigs() { return executionConfigs; } public void setExecutionConfigs(List<ExecutionConfigBE> executionConfigs) { this.executionConfigs = executionConfigs; } }
23.569231
96
0.745431
b4480ee4b676c26797dfebaeb7df11642f80bf07
422
package app.datamodel.pojos.enums; public enum StorablePojoState { INIT, /* The MongoDB driver has created the POJO class and it is filling its fields */ IGNORED, /* Ignored (detached) POJO. Modifications will not be registered and saved */ UNTRACKED, /* Newly created POJO, still not saved */ STAGED, /* POJO contains some unsaved modifications */ COMMITTED /* POJO is up-to-date with the document in the db */ }
38.363636
88
0.739336
4f4bdc3a0a0d8ad987ec98a7c86618d562bb061c
218
package p; /** * Packet 14 Request Window serverbound * * @author sn * */ public class Packet14 extends Packet { @PacketField private final int id = 14; @PacketField private String spatialID; }
14.533333
40
0.655963
ae63e0e66f856ec1dfa6c6e17d6256f5f9baf74b
976
package com.hl.module_shoppingcart.model.bean; import com.hl.anotation.NotProguard; import com.hl.base_module.adapter.BaseMulDataModel; @NotProguard public class GettedGiftItemBean extends BaseMulDataModel { private int id; private String name; private String price; private int number; private String flag; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } }
18.074074
58
0.607582
02b061e6b9f78c15b8d1183efde107c48b518722
4,159
package sample.http; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedHashMap; import common.data.JsonObject; import common.TextUtil; import core.http.HttpMethod; import core.http.HttpRequest; import core.http.HttpResponse; import core.http.HttpUrl; import core.http.IWebServiceLogic; public class RestWebService implements IWebServiceLogic{ private LinkedHashMap<String, JsonObject> memCache = new LinkedHashMap<String, JsonObject>(); /*** * Send response message of printing certain json information to user in specific url. */ public HttpResponse Respond(HttpRequest request){ String url = request.getUrlPath(); HttpMethod method = request.getRequestType(); String returnValue = ""; if(method.equals(HttpMethod.GET)){ returnValue = GET(url); }else if(method.equals(HttpMethod.POST)){ returnValue = POST(request); } HttpResponse response = new HttpResponse(200, "OK"); response.setHeaderProperty("Content-Type", "application/json;charset=utf-8"); response.setHeaderProperty("Content-Length", String.valueOf(returnValue.length() + 2)); response.setHeaderProperty("Cache-Control", "no-cache"); response.setMessageBody(returnValue); return response; } //User-defined function do like this. private String GET(String url){ String val = MockDatabase(url); if(val == null) return ""; return val; } //User-defined function do like also this. private String POST(HttpRequest req){ String returnMsg = "Success to save in server!"; try{ String name = ""; String grade = ""; String age = ""; HttpUrl reqUrl = req.getUrl(); //It depends on api speculations. name = reqUrl.getPathElement(1); grade = ClassifyGrade(reqUrl.getPathElement(2)); age = reqUrl.getPathElement(3); JsonObject jobj = new JsonObject(); jobj.PutElement("name", name); jobj.PutElement("grade", grade); jobj.PutElement("age", Integer.parseInt(age)); ArrayList<Object> friends = CallFriends(name); jobj.PutElement("friends", friends); LinkedHashMap<String, Object> score = ReadScore(name); jobj.PutElement("score", score); memCache.put(req.getUrlPath(), jobj); }catch(Exception e){ returnMsg = "Failed to save in server. maybe there is an error."; } return returnMsg; } private String ClassifyGrade(String part){ String grade = ""; if(part.equals("1")){ grade = "freshman"; }else if(part.equals("2")){ grade = "sophomore"; }else if(part.equals("3")){ grade = "junior"; }else if(part.equals("4")){ grade = "senior"; }else{ grade = "unranked"; } return grade; } /*** * Set dummy friends in student that of given name. * @param name * @return */ private ArrayList<Object> CallFriends(String name){ ArrayList<Object> friends = new ArrayList<Object>(); if(name.equals("tomas")){ friends.add("mike"); friends.add("james"); friends.add("rollen"); }else if(name.equals("james")){ friends.add("tomas"); friends.add("kate"); friends.add("teddy"); }else if(name.equals("rollen")){ friends.add("nichole"); friends.add("tomas"); friends.add("sara"); } return friends; } /*** * Set dummy scores in student that of given name. * @param name * @return */ private LinkedHashMap<String, Object> ReadScore(String name){ LinkedHashMap<String, Object> score = new LinkedHashMap<String, Object>(); if(name.equals("tomas")){ score.put("math", 100); score.put("english", 97); score.put("science", 78); }else if(name.equals("james")){ score.put("math", 80); score.put("english", 77); score.put("science", 100); }else if(name.equals("rollen")){ score.put("math", 60); score.put("english", 100); score.put("science", 90); } return score; } /*** * This method mimics the action that of selecting data from database from given query. * @param query * @return */ private String MockDatabase(String url){ if(memCache.containsKey(url)){ JsonObject jobj = memCache.get(url); String result = jobj.Stringify(); return result; } return null; } }
24.609467
94
0.675162
af5c94b0fdb751f85e2e58fe98a70ac82bd4fea0
539
package com.spring.model.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.model.dao.DepartmentDao; import com.spring.model.service.DepartmentService; @Service("departmentServiceImpl") public class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentDao departmentDao; @Override public List<String> getAll() { List<String> names = departmentDao.getNames(); return names; } }
22.458333
65
0.801484
5716419f8a87f90d264442f9950344c9855643ba
1,898
package zener.zcomm.gui.zcomm_nr; import io.github.cottonmc.cotton.gui.networking.NetworkSide; import io.github.cottonmc.cotton.gui.networking.ScreenNetworking; import io.github.cottonmc.cotton.gui.widget.WTextField; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import zener.zcomm.Main; import zener.zcomm.util.nrCheck; public class NRConfirm implements Runnable { public PlayerInventory playerInventory; public ItemStack zcommItemStack; public WTextField NR_Field; public zcommNRGUIDescription zcommNRGUIDescription; public NRConfirm(zcommNRGUIDescription zcommNRGUIDescription, PlayerInventory playerInventory, ItemStack zcommItemStack, WTextField NR_Field) { this.playerInventory = playerInventory; this.zcommItemStack = zcommItemStack; this.NR_Field = NR_Field; this.zcommNRGUIDescription = zcommNRGUIDescription; } public void run() { String text = NR_Field.getText(); nrCheck nrcheck = new nrCheck(text); if (!nrcheck.isNr()) { NR_Field.setSuggestion("Not a number"); NR_Field.setText(""); return; } if (nrcheck.isLengthLong()) { NR_Field.setSuggestion("Too long"); NR_Field.setText(""); return; } if (nrcheck.isLengthShort()) { NR_Field.setSuggestion("Too short"); NR_Field.setText(""); return; } if (nrcheck.isNegative()) { NR_Field.setSuggestion("Negative"); NR_Field.setText(""); return; } ScreenNetworking.of(zcommNRGUIDescription, NetworkSide.CLIENT).send(new Identifier(Main.ID, "set_nr"), buf -> buf.writeInt(nrcheck.getNr())); } }
32.169492
150
0.64647
8a66e5e3fac68134f739ea52f6917ff12b7dad46
2,691
package org.radargun.util; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author Matej Cimbora */ public class MapReduceTraitRepository extends CoreTraitRepository { public static Map<Class<?>, Object> getAllTraits() { Map<Class<?>, Object> traitMap = new HashMap<>(CoreTraitRepository.getAllTraits()); ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap(); traitMap.put(org.radargun.traits.MapReducer.class, new MapReducer(concurrentHashMap)); return traitMap; } public static class MapReducer implements org.radargun.traits.MapReducer { private ConcurrentHashMap cache; public MapReducer(ConcurrentHashMap cache) { this.cache = cache; } @Override public Builder builder() { return new Builder(cache); } @Override public boolean supportsCombiner() { return true; } @Override public boolean supportsTimeout() { return true; } private static class Builder implements org.radargun.traits.MapReducer.Builder { private ConcurrentHashMap cache; public Builder(ConcurrentHashMap cache) { this.cache = cache; } @Override public Builder timeout(long timeout) { return this; } @Override public org.radargun.traits.MapReducer.Builder source(String source) { return this; } @Override public Task build() { return new Task(cache); } @Override public Builder collator(String collatorFqn, Collection collatorParameters) { return this; } @Override public Builder combiner(String combinerFqn, Collection combinerParameters) { return this; } @Override public Builder reducer(String reducerFqn, Collection reducerParameters) { return this; } @Override public Builder mapper(String mapperFqn, Collection mapperParameters) { return this; } } private static class Task implements org.radargun.traits.MapReducer.Task { private ConcurrentHashMap cache; public Task(ConcurrentHashMap cache) { this.cache = cache; } @Override public Map execute() { return Collections.unmodifiableMap(cache); } @Override public Object executeWithCollator() { return cache.size(); } } } }
24.916667
92
0.613527
f5f55f1db90de7b2b60576d407184686622a9295
4,537
package io.github.pramcharan.wd.binary.downloader.download; import io.github.pramcharan.wd.binary.downloader.domain.OsEnvironment; import io.github.pramcharan.wd.binary.downloader.domain.URLLookup; import io.github.pramcharan.wd.binary.downloader.enums.TargetArch; import io.github.pramcharan.wd.binary.downloader.enums.CompressedBinaryType; import io.github.pramcharan.wd.binary.downloader.enums.OsType; import io.github.pramcharan.wd.binary.downloader.exception.WebDriverBinaryDownloaderException; import io.github.pramcharan.wd.binary.downloader.utils.HttpUtils; import io.github.pramcharan.wd.binary.downloader.utils.TempFileUtils; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.function.Function; public class GeckoBinaryDownloadProperties implements BinaryDownloadProperties { private String release; private TargetArch targetArch; private final String BINARY_DOWNLOAD_URL_TAR_PATTERN = "%s/%s/geckodriver-%s-%s.tar.gz"; private final String BINARY_DOWNLOAD_URL_ZIP_PATTERN = "%s/%s/geckodriver-%s-%s.zip"; private GeckoBinaryDownloadProperties() { release = getLatestRelease(); if (release.length() == 0) { throw new WebDriverBinaryDownloaderException("Unable to read the latest GeckoDriver release from: " + URLLookup.GECKODRIVER_LATEST_RELEASE_URL); } } private GeckoBinaryDownloadProperties(String release) { this.release = release; } public static GeckoBinaryDownloadProperties forLatestRelease() { return new GeckoBinaryDownloadProperties(); } public static GeckoBinaryDownloadProperties forPreviousRelease(String release) { return new GeckoBinaryDownloadProperties(release); } @Override public URL getDownloadURL() { try { return new URL(String.format( binaryDownloadPattern.apply(getBinaryEnvironment()), URLLookup.GECKODRIVER_URL, release, release, osNameAndArc.apply(getBinaryEnvironment()))); } catch (MalformedURLException e) { throw new WebDriverBinaryDownloaderException(e); } } private Function<OsEnvironment, String> binaryDownloadPattern = (osEnvironment) -> { if (osEnvironment.getOsType().equals(OsType.WIN)) { return BINARY_DOWNLOAD_URL_ZIP_PATTERN; } else { return BINARY_DOWNLOAD_URL_TAR_PATTERN; } }; private Function<OsEnvironment, String> osNameAndArc = (osEnvironment) -> { if (osEnvironment.getOsType().equals(OsType.MAC)) { return "macos"; } else { return osEnvironment.getOsNameAndArch(); } }; private Function<OsEnvironment, String> compressedBinaryExt = (osEnvironment) -> osEnvironment.getOsType().equals(OsType.WIN) ? "zip" : "tar.gz"; @Override public OsEnvironment getBinaryEnvironment() { return targetArch != null ? OsEnvironment.create(targetArch.getValue()) : OsEnvironment.create(); } @Override public File getCompressedBinaryFile() { return new File(String.format("%s/geckodriver_%s.%s", TempFileUtils.getTempDirectory(), release, compressedBinaryExt.apply(getBinaryEnvironment()))); } @Override public CompressedBinaryType getCompressedBinaryType() { return getBinaryEnvironment().getOsType().equals(OsType.WIN) ? CompressedBinaryType.ZIP : CompressedBinaryType.TAR; } @Override public String getBinaryFilename() { return getBinaryEnvironment().getOsType().equals(OsType.WIN) ? "geckodriver.exe" : "geckodriver"; } public String getBinaryDirectory() { return release != null ? "geckodriver_" + release : "geckodriver"; } @Override public String getBinaryDriverName() { return "GeckoDriver"; } @Override public String getBinaryVersion() { return release; } @Override public void setBinaryArchitecture(TargetArch targetArch) { this.targetArch = targetArch; } private String getLatestRelease() { final String releaseLocation = HttpUtils.getLocation(URLLookup.GECKODRIVER_LATEST_RELEASE_URL); if (releaseLocation == null || releaseLocation.length() < 2 || !releaseLocation.contains("/")) { return ""; } return releaseLocation.substring(releaseLocation.lastIndexOf("/") + 1); } }
35.724409
156
0.689442
456ff635fe98534af496ce9e3e6b4566f0d254d3
12,849
package uk.gov.hmcts.ccd.domain.service.search.elasticsearch; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import uk.gov.hmcts.ccd.domain.model.search.elasticsearch.ElasticsearchRequest; import uk.gov.hmcts.ccd.endpoint.exceptions.BadSearchRequest; import java.util.Arrays; import java.util.List; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; 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 uk.gov.hmcts.ccd.domain.model.search.elasticsearch.ElasticsearchRequest.SOURCE; class CrossCaseTypeSearchRequestTest { private final ObjectMapper objectMapper = new ObjectMapper(); private static final String NAME = "name"; private static final String ALIAS_NAME = "alias." + NAME; private static final String SEARCH_REQUEST_SIMPLE_JSON = "{\"query\":{}}"; private static final String SEARCH_REQUEST_WITH_SOURCE_JSON = "{\"_source\":[\"" + ALIAS_NAME + "\"], \"query\":{}}"; @Test @DisplayName("should throw exception when query node not found") void shouldThrowExceptionWhenQueryNodeNotFound() throws JsonProcessingException { // ARRANGE String query = "{}"; // ACT / ASSERT CrossCaseTypeSearchRequest.Builder builder = new CrossCaseTypeSearchRequest.Builder() .withCaseTypes(singletonList("caseType")) .withSearchRequest(new ElasticsearchRequest(objectMapper.readValue(query, JsonNode.class))); assertThrows(BadSearchRequest.class, builder::build); } @Nested @DisplayName("builder") class Builder { @Test @DisplayName("should build non-multi-case-type search request") void shouldBuildNonMultiCaseTypeSearch() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_SIMPLE_JSON)); List<String> caseTypeIds = singletonList("CT"); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(false)); assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequest.getNativeSearchRequest())); assertThat(request.getCaseTypeIds(), hasSize(1)); assertThat(request.getAliasFields().isEmpty(), is(true)); assertThat(request.getSearchIndex().isPresent(), is(false)); } @Test @DisplayName("should build multi-case-type search request") void shouldBuildMultiCaseTypeSearch() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_WITH_SOURCE_JSON)); List<String> caseTypeIds = Arrays.asList("CT", "PT"); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .withMultiCaseTypeSearch(true) .build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(true)); assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequest.getNativeSearchRequest())); assertNull(request.getSearchRequestJsonNode().get(SOURCE)); // i.e. SOURCE should be cleared assertThat(request.getCaseTypeIds(), is(caseTypeIds)); assertThat(request.getAliasFields(), hasItem(NAME)); assertThat(request.getSearchIndex().isPresent(), is(false)); } @Test @DisplayName("should build search request: but skip auto-population of alias fields if using fixed SearchIndex") void shouldBuildButSkipAutoPopulationOfAliasFieldsIfSearchIndexIsSet() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_WITH_SOURCE_JSON)); List<String> caseTypeIds = Arrays.asList("CT", "PT"); SearchIndex searchIndex = createSearchIndex(); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .withMultiCaseTypeSearch(true) .withSearchIndex(searchIndex) .build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(true)); assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequest.getNativeSearchRequest())); assertNotNull(request.getSearchRequestJsonNode().get(SOURCE)); // i.e. SOURCE should be retained JSONAssert.assertEquals( "[\"" + ALIAS_NAME + "\"]", request.getSearchRequestJsonNode().get(SOURCE).toString(), JSONCompareMode.LENIENT ); assertThat(request.getCaseTypeIds(), is(caseTypeIds)); assertThat(request.getAliasFields().isEmpty(), is(true)); assertThat(request.getSearchIndex().isPresent(), is(true)); assertThat(request.getSearchIndex().get(), is(searchIndex)); } } @Nested @DisplayName("clone builder") class CloneBuilder { @Test @DisplayName("should build a clone of a non-multi-case-type search request") void shouldBuildACloneOfANonMultiCaseTypeSearch() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_SIMPLE_JSON)); List<String> caseTypeIds = singletonList("CT"); CrossCaseTypeSearchRequest originalRequest = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .build(); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder(originalRequest).build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(false)); assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequest.getNativeSearchRequest())); assertThat(request.getCaseTypeIds(), hasSize(1)); assertThat(request.getAliasFields().isEmpty(), is(true)); } @Test @DisplayName("should build a clone of a multi-case-type search request") void shouldBuildACloneOfAMultiCaseTypeSearch() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_WITH_SOURCE_JSON)); List<String> caseTypeIds = Arrays.asList("CT", "PT"); CrossCaseTypeSearchRequest originalRequest = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .withMultiCaseTypeSearch(true) .build(); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder(originalRequest).build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(true)); assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequest.getNativeSearchRequest())); assertNull(request.getSearchRequestJsonNode().get(SOURCE)); // i.e. SOURCE should be cleared assertThat(request.getCaseTypeIds(), is(caseTypeIds)); assertThat(request.getAliasFields(), hasItem(NAME)); // i.e. populated with alias from SOURCE assertThat(request.getSearchIndex().isPresent(), is(false)); } @Test @DisplayName("should build a clone of a search request: but allow overrides") void shouldBuildACloneOfASearchRequestWithOverrides() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_SIMPLE_JSON)); List<String> caseTypeIds = Arrays.asList("CT", "PT"); List<String> aliasFields = Arrays.asList("field1", "field2"); SearchIndex searchIndex = createSearchIndex(); CrossCaseTypeSearchRequest originalRequest = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .withMultiCaseTypeSearch(true) .withSourceFilterAliasFields(aliasFields) .withSearchIndex(searchIndex) .build(); // overrides ElasticsearchRequest elasticsearchRequestOverride = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_WITH_SOURCE_JSON)); List<String> caseTypeIdsOverride = singletonList("CT-override"); List<String> aliasFieldsOverride = Arrays.asList("field1-override", "field2-override"); SearchIndex searchIndexOverride = new SearchIndex( "my_index_name_override", "my_index_type_override" ); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder(originalRequest) .withSearchRequest(elasticsearchRequestOverride) .withCaseTypes(caseTypeIdsOverride) .withSourceFilterAliasFields(aliasFieldsOverride) .withSearchIndex(searchIndexOverride) .build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(false)); // NB: now a single cate type search assertThat(request.getSearchRequestJsonNode(), is(elasticsearchRequestOverride.getNativeSearchRequest())); assertThat(request.getCaseTypeIds(), is(caseTypeIdsOverride)); assertThat(request.getAliasFields(), is(aliasFieldsOverride)); assertThat(request.getSearchIndex().isPresent(), is(true)); assertThat(request.getSearchIndex().get(), is(searchIndexOverride)); } @Test @DisplayName("should build a clone of a search request: but allow some overrides set to null") void shouldBuildACloneOfASearchRequestWithOverridesSetToNull() throws Exception { // ARRANGE ElasticsearchRequest elasticsearchRequest = new ElasticsearchRequest(objectMapper.readTree(SEARCH_REQUEST_SIMPLE_JSON)); List<String> caseTypeIds = Arrays.asList("CT", "PT"); List<String> aliasFields = Arrays.asList("field1", "field2"); SearchIndex searchIndex = createSearchIndex(); CrossCaseTypeSearchRequest originalRequest = new CrossCaseTypeSearchRequest.Builder() .withSearchRequest(elasticsearchRequest) .withCaseTypes(caseTypeIds) .withMultiCaseTypeSearch(true) .withSourceFilterAliasFields(aliasFields) .withSearchIndex(searchIndex) .build(); // ACT CrossCaseTypeSearchRequest request = new CrossCaseTypeSearchRequest.Builder(originalRequest) .withCaseTypes(null) .withSourceFilterAliasFields(null) .withSearchIndex(null) .build(); // ASSERT assertThat(request.isMultiCaseTypeSearch(), is(false)); // i.e. reset to default after null case types assertThat(request.getCaseTypeIds().isEmpty(), is(true)); assertThat(request.getAliasFields().isEmpty(), is(true)); assertThat(request.getSearchIndex().isPresent(), is(false)); } } private SearchIndex createSearchIndex() { return new SearchIndex( "my_index_name", "my_index_type" ); } }
44.926573
120
0.662075
7ef96905143d7f70821829c1edf051c89b1d6b82
455
package main.sqlipa.ast.expr; import main.sqlipa.ast.Block; public abstract class InExpr extends Expression { public enum Operator { IN, NOT_IN } public Operator operator; public Expression expr; public InExpr() { super(); } public InExpr(Block block, Operator operator, Expression expr) { super(block); this.operator = operator; this.expr = expr; } }
17.5
68
0.591209
392302c1f2c8dbf05dbd98af63e25ca0e3e993f3
4,135
package seedu.tinner.model.reminder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.tinner.testutil.Assert.assertThrows; import static seedu.tinner.testutil.TypicalReminders.AMAZON_DATA_ENGINEER; import static seedu.tinner.testutil.TypicalReminders.APPLE_ML_ENGINEER; import static seedu.tinner.testutil.TypicalReminders.GOOGLE_FRONTEND; import static seedu.tinner.testutil.TypicalReminders.META_DATA_ANALYSIS; import java.time.LocalDate; import java.util.ArrayList; import org.junit.jupiter.api.Test; import seedu.tinner.model.reminder.exceptions.DuplicateReminderException; import seedu.tinner.testutil.ReminderBuilder; public class UniqueReminderListTest { private final UniqueReminderList reminderList = UniqueReminderList.getInstance(); @Test public void contains_nullReminder_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> reminderList.contains(null)); } @Test public void contains_reminderNotInList_returnsFalse() { Reminder test = new ReminderBuilder() .withCompanyName("No such company") .withRoleName("Nothing") .build(); assertFalse(reminderList.contains(test)); } @Test public void contains_existingReminder_returnsTrue() { Reminder test = new ReminderBuilder() .withCompanyName("Some Company") .withRoleName("Backend Developer") .build(); reminderList.add(test); assertTrue(reminderList.contains(test)); } @Test public void contains_reminderWithSameIdentity_returnsTrue() { Reminder test = new ReminderBuilder() .withCompanyName("Test Company") .withRoleName("Frontend Developer") .withStatus("complete") .withReminderDate("30-10-2022 23:59") .build(); Reminder test2 = new ReminderBuilder() .withCompanyName("Test Company") .withRoleName("Frontend Developer") .withStatus("pending") .withReminderDate("30-11-2022 23:59") .build(); reminderList.add(test); assertTrue(reminderList.contains(test2)); } @Test public void add_nullReminder_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> reminderList.add(null)); } @Test public void add_duplicateReminder_throwsDuplicateReminderException() { reminderList.add(META_DATA_ANALYSIS); assertThrows(DuplicateReminderException.class, () -> reminderList.add(META_DATA_ANALYSIS)); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> reminderList.asUnmodifiableObservableList().remove(0)); } @Test public void getDateSpecificReminders_existingReminders_returnAllMatching() { reminderList.add(APPLE_ML_ENGINEER); reminderList.add(GOOGLE_FRONTEND); reminderList.add(AMAZON_DATA_ENGINEER); ArrayList<Reminder> expectedList = new ArrayList<>(); expectedList.add(APPLE_ML_ENGINEER); expectedList.add(GOOGLE_FRONTEND); LocalDate date = GOOGLE_FRONTEND.getReminderDate().value.toLocalDate(); assertEquals(expectedList, reminderList.getDateSpecificReminders(date)); } @Test public void getDateSpecificReminders_noRemindersOnDate_returnEmptyList() { Reminder test = new ReminderBuilder() .withCompanyName("Company C") .withRoleName("Frontend Developer") .withReminderDate("02-02-2024 00:00") .build(); reminderList.add(test); ArrayList<Reminder> expectedList = new ArrayList<>(); LocalDate date = LocalDate.of(2024, 01, 01); assertEquals(expectedList, reminderList.getDateSpecificReminders(date)); } }
37.93578
99
0.691173
46ea9072d40e1b7dd93820aeef75c2a9bb2e5752
1,546
package Stream; import java.util.Arrays; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; public class TestOptionalStream3 { public static void main(String[] args) { test1(); } public static void test1() { OptionalFlatMap.test("Add brackets", s -> Optional.of("[" + s + "]")); OptionalFlatMap.test("Increment", s -> { try { return Optional.of( Integer.parseInt(s) + 1 + ""); } catch (NumberFormatException e) { return Optional.of(s); } }); OptionalFlatMap.test("Replace", s -> Optional.of(s.replace("2", "9"))); OptionalFlatMap.test("Take last digit", s -> Optional.of(s.length() > 0 ? s.charAt(s.length() - 1) + "" : s)); System.out.println(); } } class OptionalFlatMap { static String[] elements = {"12", "", "23", "45"}; static Stream<String> testStream() { return Arrays.stream(elements); } static void test(String descr, Function<String, Optional<String>> func) { System.out.println(" ---( " + descr + " )---"); for (int i = 0; i <= elements.length; i++) { System.out.println( testStream() .skip(i) .findFirst() .flatMap(func)); } } }
26.655172
63
0.472833
df2f7450b108265c5855697f8f42319a784dcb27
2,907
package com.vansuita.gaussianblur.sample.act; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatSeekBar; import android.support.v7.widget.Toolbar; import android.widget.SeekBar; import android.widget.TextView; import com.vansuita.gaussianblur.GaussianBlur; import com.vansuita.gaussianblur.sample.R; import com.vansuita.gaussianblur.sample.adpt.DinosaurPagerAdapter; import com.vansuita.gaussianblur.sample.lis.IOnSettingsChanged; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { private List<IOnSettingsChanged> listeners = new ArrayList(); private AppCompatSeekBar sbRadius; private AppCompatSeekBar sbSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(new DinosaurPagerAdapter(getSupportFragmentManager(), this)); ((TabLayout) findViewById(R.id.tabs)).setupWithViewPager(viewPager); sbRadius = (AppCompatSeekBar) findViewById(R.id.radius); sbSize = (AppCompatSeekBar) findViewById(R.id.size); sbRadius.setTag(R.id.label, findViewById(R.id.radius_label)); sbSize.setTag(R.id.label, findViewById(R.id.size_label)); sbRadius.setTag(R.id.label_title, R.string.radius); sbSize.setTag(R.id.label_title, R.string.size); sbRadius.setOnSeekBarChangeListener(this); sbSize.setOnSeekBarChangeListener(this); sbSize.setMax(GaussianBlur.MAX_RADIUS); sbSize.setMax(GaussianBlur.MAX_SIZE); sbRadius.setProgress(GaussianBlur.MAX_RADIUS); sbSize.setProgress(GaussianBlur.MAX_SIZE); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { ((TextView) seekBar.getTag(R.id.label)).setText(getString((Integer) seekBar.getTag(R.id.label_title), progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { //No code, not used. } @Override public void onStopTrackingTouch(SeekBar seekBar) { for (IOnSettingsChanged l : listeners) l.onChanged(); } public int getActualRadius() { return sbRadius.getProgress(); } public int getActualMaxSize() { return sbSize.getProgress(); } public void addOnSettingsChanged(IOnSettingsChanged listener) { listeners.add(listener); } public void removeOnSettingsChanged(IOnSettingsChanged listener) { listeners.remove(listener); } }
31.945055
121
0.729962
4779f54d798dac3d76b8a9852e4b894db82ca693
2,062
package com.quickblox.sample.pushnotifications.activities; import android.os.Bundle; import android.view.View; import com.quickblox.auth.QBAuth; import com.quickblox.auth.model.QBSession; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.sample.core.ui.activity.CoreSplashActivity; import com.quickblox.sample.core.utils.constant.GcmConsts; import com.quickblox.sample.pushnotifications.App; import com.quickblox.sample.pushnotifications.R; import com.quickblox.sample.pushnotifications.utils.Consts; import com.quickblox.users.model.QBUser; public class SplashActivity extends CoreSplashActivity { private String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras != null) { message = getIntent().getExtras().getString(GcmConsts.EXTRA_GCM_MESSAGE); } createSession(); } private void createSession() { QBUser qbUser = new QBUser(Consts.USER_LOGIN, Consts.USER_PASSWORD); QBAuth.createSession(qbUser, new QBEntityCallback<QBSession>() { @Override public void onSuccess(QBSession qbSession, Bundle bundle) { App.getInstance().setCurrentUserId(qbSession.getUserId()); proceedToTheNextActivity(); } @Override public void onError(QBResponseException e) { showSnackbarError(null, R.string.splash_create_session_error, e, new View.OnClickListener() { @Override public void onClick(View v) { createSession(); } }); } }); } @Override protected String getAppName() { return getString(R.string.app_title); } @Override protected void proceedToTheNextActivity() { MessagesActivity.start(this, message); finish(); } }
32.730159
109
0.663434
3dc444c7e22c9ba64ffb35c5a73894cd8ce5ccc7
1,191
/*Authors:Sourlantzis Dimitrios , AEM:9868, Phone number:6955757756 - 6948703383, e-mail:[email protected] * Sidiropoulos Evripidis, AEM:9679, Phone number:6971947855, e-mail:[email protected] */ public class Trap { private int id; private int x; private int y; private String type; private int points; public Trap() { this.id = -1; this.x = 0; this.y = 0; this.type = ""; this.points = 0; } public Trap(int id, int x, int y, String type, int points) { this.id = id; this.x = x; this.y = y; this.type = type; this.points = points; } public Trap(Trap t) { this.id = t.id; this.x = t.x; this.y = t.y; this.type = t.type; this.points = t.points; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } }
15.075949
109
0.609572
62fd4f971db1a1b9f4c57a0266aed3270ecf5eea
38,204
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.eclipse.imagen.media.opimage; import java.awt.Rectangle; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.util.Map; import org.eclipse.imagen.BorderExtender; import org.eclipse.imagen.ImageLayout; import org.eclipse.imagen.Interpolation; import org.eclipse.imagen.InterpolationTable; import org.eclipse.imagen.RasterAccessor; import org.eclipse.imagen.RasterFormatTag; import org.eclipse.imagen.ScaleOpImage; import org.eclipse.imagen.media.util.Rational; // import org.eclipse.imagen.media.test.OpImageTester; /** * An <code>OpImage</code> that performs bicubic interpolation scaling. * */ final class ScaleBicubicOpImage extends ScaleOpImage { /* The number of subsampleBits */ private int subsampleBits; /* 2 ^ subsampleBits */ private int one; /** The horizontal coefficient data in fixed-point format. */ private int[] tableDataHi = null; /** The vertical coefficient data in fixed-point format. */ private int[] tableDataVi = null; /** The horizontal coefficient data in floating-point format. */ private float[] tableDataHf = null; /** The vertical coefficient data in floating-point format. */ private float[] tableDataVf = null; /** The horizontal coefficient data in double format. */ private double[] tableDataHd = null; /** The vertical coefficient data in double format. */ private double[] tableDataVd = null; /** Number of fractional bits used to described filter coefficients. */ private int precisionBits; /** The number 1/2 with precisionBits of fractional precision. */ private int round; private Rational half = new Rational(1, 2); // The InterpolationTable superclass. InterpolationTable interpTable; long invScaleYInt, invScaleYFrac; long invScaleXInt, invScaleXFrac; /** * Constructs a ScaleBicubicOpImage from a RenderedImage source, * * @param source a RenderedImage. * @param extender a BorderExtender, or null. * @param layout an ImageLayout optionally containing the tile grid layout, * SampleModel, and ColorModel, or null. * @param xScale scale factor along x axis. * @param yScale scale factor along y axis. * @param xTrans translation factor along x axis. * @param yTrans translation factor along y axis. * @param interp a Interpolation object to use for resampling. */ public ScaleBicubicOpImage(RenderedImage source, BorderExtender extender, Map config, ImageLayout layout, float xScale, float yScale, float xTrans, float yTrans, Interpolation interp) { super(source, layout, config, true, extender, interp, xScale, yScale, xTrans, yTrans); subsampleBits = interp.getSubsampleBitsH(); interpTable = (InterpolationTable)interp; // Number of subsample positions one = 1 << subsampleBits; precisionBits = interpTable.getPrecisionBits(); if (precisionBits > 0) { round = 1<< (precisionBits - 1); } if (invScaleYRational.num > invScaleYRational.denom) { invScaleYInt = invScaleYRational.num / invScaleYRational.denom; invScaleYFrac = invScaleYRational.num % invScaleYRational.denom; } else { invScaleYInt = 0; invScaleYFrac = invScaleYRational.num; } if (invScaleXRational.num > invScaleXRational.denom) { invScaleXInt = invScaleXRational.num / invScaleXRational.denom; invScaleXFrac = invScaleXRational.num % invScaleXRational.denom; } else { invScaleXInt = 0; invScaleXFrac = invScaleXRational.num; } } /** * Performs a scale operation on a specified rectangle. The sources are * cobbled. * * @param sources an array of source Rasters, guaranteed to provide all * necessary source data for computing the output. * @param dest a WritableRaster containing the area to be computed. * @param destRect the rectangle within dest to be processed. */ protected void computeRect(Raster [] sources, WritableRaster dest, Rectangle destRect) { // Retrieve format tags. RasterFormatTag[] formatTags = getFormatTags(); Raster source = sources[0]; // Get the source rectangle Rectangle srcRect = source.getBounds(); int srcRectX = srcRect.x; int srcRectY = srcRect.y; RasterAccessor srcAccessor = new RasterAccessor(source, srcRect, formatTags[0], getSource(0).getColorModel()); RasterAccessor dstAccessor = new RasterAccessor(dest, destRect, formatTags[1], getColorModel()); // Loop variables based on the destination rectangle to be calculated. int dx = destRect.x; int dy = destRect.y; int dwidth = destRect.width; int dheight = destRect.height; int srcPixelStride = srcAccessor.getPixelStride(); int srcScanlineStride = srcAccessor.getScanlineStride(); int[] ypos = new int[dheight]; int[] xpos = new int[dwidth]; // Precalculate the y positions and store them in an array. int[] yfracvalues = new int[dheight]; // Precalculate the x positions and store them in an array. int[] xfracvalues = new int[dwidth]; long syNum = dy, syDenom = 1; // Subtract the X translation factor sy -= transY syNum = syNum * transYRationalDenom - transYRationalNum * syDenom; syDenom *= transYRationalDenom; // Add 0.5 syNum = 2 * syNum + syDenom; syDenom *= 2; // Multply by invScaleX syNum *= invScaleYRationalNum; syDenom *= invScaleYRationalDenom; // Subtract 0.5 syNum = 2 * syNum - syDenom; syDenom *= 2; // Separate the x source coordinate into integer and fractional part int srcYInt = Rational.floor(syNum , syDenom); long srcYFrac = syNum % syDenom; if (srcYInt < 0) { srcYFrac = syDenom + srcYFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleY long commonYDenom = syDenom * invScaleYRationalDenom; srcYFrac *= invScaleYRationalDenom; long newInvScaleYFrac = invScaleYFrac * syDenom; long sxNum = dx, sxDenom = 1; // Subtract the X translation factor sx -= transX sxNum = sxNum * transXRationalDenom - transXRationalNum * sxDenom; sxDenom *= transXRationalDenom; // Add 0.5 sxNum = 2 * sxNum + sxDenom; sxDenom *= 2; // Multply by invScaleX sxNum *= invScaleXRationalNum; sxDenom *= invScaleXRationalDenom; // Subtract 0.5 sxNum = 2 * sxNum - sxDenom; sxDenom *= 2; // Separate the x source coordinate into integer and fractional part // int part is floor(sx), frac part is sx - floor(sx) int srcXInt = Rational.floor(sxNum , sxDenom); long srcXFrac = sxNum % sxDenom; if (srcXInt < 0) { srcXFrac = sxDenom + srcXFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleX long commonXDenom = sxDenom * invScaleXRationalDenom; srcXFrac *= invScaleXRationalDenom; long newInvScaleXFrac = invScaleXFrac * sxDenom; for (int i=0; i<dwidth; i++) { xpos[i] = (srcXInt - srcRectX) * srcPixelStride; xfracvalues[i] = (int)(((float)srcXFrac/(float)commonXDenom) * one); // Move onto the next source pixel. // Add the integral part of invScaleX to the integral part // of srcX srcXInt += invScaleXInt; // Add the fractional part of invScaleX to the fractional part // of srcX srcXFrac += newInvScaleXFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcXFrac >= commonXDenom) { srcXInt += 1; srcXFrac -= commonXDenom; } } for (int i = 0; i < dheight; i++) { // Calculate the source position in the source data array. ypos[i] = (srcYInt - srcRectY) * srcScanlineStride; // Calculate the yfrac value yfracvalues[i] = (int)(((float)srcYFrac/(float)commonYDenom) * one); // Move onto the next source pixel. // Add the integral part of invScaleY to the integral part // of srcY srcYInt += invScaleYInt; // Add the fractional part of invScaleY to the fractional part // of srcY srcYFrac += newInvScaleYFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcYFrac >= commonYDenom) { srcYInt += 1; srcYFrac -= commonYDenom; } } switch (dstAccessor.getDataType()) { case DataBuffer.TYPE_BYTE: initTableDataI(); byteLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; case DataBuffer.TYPE_SHORT: initTableDataI(); shortLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; case DataBuffer.TYPE_USHORT: initTableDataI(); ushortLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; case DataBuffer.TYPE_INT: initTableDataI(); intLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; case DataBuffer.TYPE_FLOAT: initTableDataF(); floatLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; case DataBuffer.TYPE_DOUBLE: initTableDataD(); doubleLoop(srcAccessor, destRect, dstAccessor, xpos, ypos, xfracvalues, yfracvalues); break; default: throw new RuntimeException(JaiI18N.getString("OrderedDitherOpImage0")); } // If the RasterAccessor object set up a temporary buffer for the // op to write to, tell the RasterAccessor to write that data // to the raster no that we're done with it. if (dstAccessor.isDataCopy()) { dstAccessor.clampDataArrays(); dstAccessor.copyDataToRaster(); } } private void byteLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); byte dstDataArrays[][] = dst.getByteDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); byte srcDataArrays[][] = src.getByteDataArrays(); int bandOffsets[] = src.getBandOffsets(); int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; int xfrac, yfrac; int s__, s_0, s_1, s_2; int s0_, s00, s01, s02; int s1_, s10, s11, s12; int s2_, s20, s21, s22; int s, dstOffset = 0; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { byte dstData[] = dstDataArrays[k]; byte srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow] & 0xff; s_0 = srcData[posx + posylow] & 0xff; s_1 = srcData[posxhigh + posylow] & 0xff; s_2 = srcData[posxhigh2 + posylow] & 0xff; s0_ = srcData[posxlow + posy] & 0xff; s00 = srcData[posx + posy] & 0xff; s01 = srcData[posxhigh + posy] & 0xff; s02 = srcData[posxhigh2 + posy] & 0xff; s1_ = srcData[posxlow + posyhigh] & 0xff; s10 = srcData[posx + posyhigh] & 0xff; s11 = srcData[posxhigh + posyhigh] & 0xff; s12 = srcData[posxhigh2 + posyhigh] & 0xff; s2_ = srcData[posxlow + posyhigh2] & 0xff; s20 = srcData[posx + posyhigh2] & 0xff; s21 = srcData[posxhigh + posyhigh2] & 0xff; s22 = srcData[posxhigh2 + posyhigh2] & 0xff; // Interpolate in X int offsetX = 4*xfrac; int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; long sum_ = (long)tableDataHi[offsetX]*s__; sum_ += (long)tableDataHi[offsetX1]*s_0; sum_ += (long)tableDataHi[offsetX2]*s_1; sum_ += (long)tableDataHi[offsetX3]*s_2; long sum0 = (long)tableDataHi[offsetX]*s0_; sum0 += (long)tableDataHi[offsetX1]*s00; sum0 += (long)tableDataHi[offsetX2]*s01; sum0 += (long)tableDataHi[offsetX3]*s02; long sum1 = (long)tableDataHi[offsetX]*s1_; sum1 += (long)tableDataHi[offsetX1]*s10; sum1 += (long)tableDataHi[offsetX2]*s11; sum1 += (long)tableDataHi[offsetX3]*s12; long sum2 = (long)tableDataHi[offsetX]*s2_; sum2 += (long)tableDataHi[offsetX1]*s20; sum2 += (long)tableDataHi[offsetX2]*s21; sum2 += (long)tableDataHi[offsetX3]*s22; // Intermediate rounding sum_ = (sum_ + round) >> precisionBits; sum0 = (sum0 + round) >> precisionBits; sum1 = (sum1 + round) >> precisionBits; sum2 = (sum2 + round) >> precisionBits; // Interpolate in Y int offsetY = 4*yfrac; long sum = (long)tableDataVi[offsetY]*sum_; sum += (long)tableDataVi[offsetY + 1]*sum0; sum += (long)tableDataVi[offsetY + 2]*sum1; sum += (long)tableDataVi[offsetY + 3]*sum2; s = (int)((sum + round) >> precisionBits); // clamp the value to byte range if (s > 255) { s = 255; } else if (s < 0) { s = 0; } dstData[dstPixelOffset] = (byte)(s&0xff); dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } private void shortLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); short dstDataArrays[][] = dst.getShortDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); short srcDataArrays[][] = src.getShortDataArrays(); int bandOffsets[] = src.getBandOffsets(); int dstOffset = 0; int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; int xfrac, yfrac; int s__, s_0, s_1, s_2; int s0_, s00, s01, s02; int s1_, s10, s11, s12; int s2_, s20, s21, s22; int s; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { short dstData[] = dstDataArrays[k]; short srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow]; s_0 = srcData[posx + posylow]; s_1 = srcData[posxhigh + posylow]; s_2 = srcData[posxhigh2 + posylow]; s0_ = srcData[posxlow + posy]; s00 = srcData[posx + posy]; s01 = srcData[posxhigh + posy]; s02 = srcData[posxhigh2 + posy]; s1_ = srcData[posxlow + posyhigh]; s10 = srcData[posx + posyhigh]; s11 = srcData[posxhigh + posyhigh]; s12 = srcData[posxhigh2 + posyhigh]; s2_ = srcData[posxlow + posyhigh2]; s20 = srcData[posx + posyhigh2]; s21 = srcData[posxhigh + posyhigh2]; s22 = srcData[posxhigh2 + posyhigh2]; // Interpolate in X int offsetX = 4*xfrac; int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; long sum_ = (long)tableDataHi[offsetX]*s__; sum_ += (long)tableDataHi[offsetX1]*s_0; sum_ += (long)tableDataHi[offsetX2]*s_1; sum_ += (long)tableDataHi[offsetX3]*s_2; long sum0 = (long)tableDataHi[offsetX]*s0_; sum0 += (long)tableDataHi[offsetX1]*s00; sum0 += (long)tableDataHi[offsetX2]*s01; sum0 += (long)tableDataHi[offsetX3]*s02; long sum1 = (long)tableDataHi[offsetX]*s1_; sum1 += (long)tableDataHi[offsetX1]*s10; sum1 += (long)tableDataHi[offsetX2]*s11; sum1 += (long)tableDataHi[offsetX3]*s12; long sum2 = (long)tableDataHi[offsetX]*s2_; sum2 += (long)tableDataHi[offsetX1]*s20; sum2 += (long)tableDataHi[offsetX2]*s21; sum2 += (long)tableDataHi[offsetX3]*s22; // Intermediate rounding sum_ = (sum_ + round) >> precisionBits; sum0 = (sum0 + round) >> precisionBits; sum1 = (sum1 + round) >> precisionBits; sum2 = (sum2 + round) >> precisionBits; // Interpolate in Y int offsetY = 4*yfrac; long sum = (long)tableDataVi[offsetY]*sum_; sum += (long)tableDataVi[offsetY + 1]*sum0; sum += (long)tableDataVi[offsetY + 2]*sum1; sum += (long)tableDataVi[offsetY + 3]*sum2; s = (int)((sum + round) >> precisionBits); // clamp the value to short range if (s > Short.MAX_VALUE) { s = Short.MAX_VALUE; } else if (s < Short.MIN_VALUE) { s = Short.MIN_VALUE; } dstData[dstPixelOffset] = (short)s; dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } private void ushortLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); short dstDataArrays[][] = dst.getShortDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); short srcDataArrays[][] = src.getShortDataArrays(); int bandOffsets[] = src.getBandOffsets(); int dstOffset = 0; int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; int xfrac, yfrac; int s__, s_0, s_1, s_2; int s0_, s00, s01, s02; int s1_, s10, s11, s12; int s2_, s20, s21, s22; int s; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { short dstData[] = dstDataArrays[k]; short srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow] & 0xffff; s_0 = srcData[posx + posylow] & 0xffff; s_1 = srcData[posxhigh + posylow] & 0xffff; s_2 = srcData[posxhigh2 + posylow] & 0xffff; s0_ = srcData[posxlow + posy] & 0xffff; s00 = srcData[posx + posy] & 0xffff; s01 = srcData[posxhigh + posy] & 0xffff; s02 = srcData[posxhigh2 + posy] & 0xffff; s1_ = srcData[posxlow + posyhigh] & 0xffff; s10 = srcData[posx + posyhigh] & 0xffff; s11 = srcData[posxhigh + posyhigh] & 0xffff; s12 = srcData[posxhigh2 + posyhigh] & 0xffff; s2_ = srcData[posxlow + posyhigh2] & 0xffff; s20 = srcData[posx + posyhigh2] & 0xffff; s21 = srcData[posxhigh + posyhigh2] & 0xffff; s22 = srcData[posxhigh2 + posyhigh2] & 0xffff; // Interpolate in X int offsetX = 4*xfrac; int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; long sum_ = (long)tableDataHi[offsetX]*s__; sum_ += (long)tableDataHi[offsetX1]*s_0; sum_ += (long)tableDataHi[offsetX2]*s_1; sum_ += (long)tableDataHi[offsetX3]*s_2; long sum0 = (long)tableDataHi[offsetX]*s0_; sum0 += (long)tableDataHi[offsetX1]*s00; sum0 += (long)tableDataHi[offsetX2]*s01; sum0 += (long)tableDataHi[offsetX3]*s02; long sum1 = (long)tableDataHi[offsetX]*s1_; sum1 += (long)tableDataHi[offsetX1]*s10; sum1 += (long)tableDataHi[offsetX2]*s11; sum1 += (long)tableDataHi[offsetX3]*s12; long sum2 = (long)tableDataHi[offsetX]*s2_; sum2 += (long)tableDataHi[offsetX1]*s20; sum2 += (long)tableDataHi[offsetX2]*s21; sum2 += (long)tableDataHi[offsetX3]*s22; // Intermediate rounding sum_ = (sum_ + round) >> precisionBits; sum0 = (sum0 + round) >> precisionBits; sum1 = (sum1 + round) >> precisionBits; sum2 = (sum2 + round) >> precisionBits; // Interpolate in Y int offsetY = 4*yfrac; long sum = (long)tableDataVi[offsetY]*sum_; sum += (long)tableDataVi[offsetY + 1]*sum0; sum += (long)tableDataVi[offsetY + 2]*sum1; sum += (long)tableDataVi[offsetY + 3]*sum2; s = (int)((sum + round) >> precisionBits); // clamp the value to ushort range if (s > 65536) { s = 65536; } else if (s < 0) { s = 0; } dstData[dstPixelOffset] = (short)(s & 0xffff); dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } // identical to byteLoops, except datatypes have changed. clumsy, // but there's no other way in Java private void intLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); int dstDataArrays[][] = dst.getIntDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); int srcDataArrays[][] = src.getIntDataArrays(); int bandOffsets[] = src.getBandOffsets(); int dstOffset = 0; int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; long xfrac, yfrac; int s__, s_0, s_1, s_2; int s0_, s00, s01, s02; int s1_, s10, s11, s12; int s2_, s20, s21, s22; int s; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { int dstData[] = dstDataArrays[k]; int srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow]; s_0 = srcData[posx + posylow]; s_1 = srcData[posxhigh + posylow]; s_2 = srcData[posxhigh2 + posylow]; s0_ = srcData[posxlow + posy]; s00 = srcData[posx + posy]; s01 = srcData[posxhigh + posy]; s02 = srcData[posxhigh2 + posy]; s1_ = srcData[posxlow + posyhigh]; s10 = srcData[posx + posyhigh]; s11 = srcData[posxhigh + posyhigh]; s12 = srcData[posxhigh2 + posyhigh]; s2_ = srcData[posxlow + posyhigh2]; s20 = srcData[posx + posyhigh2]; s21 = srcData[posxhigh + posyhigh2]; s22 = srcData[posxhigh2 + posyhigh2]; // Interpolate in X int offsetX = (int)(4*xfrac); int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; long sum_ = (long)tableDataHi[offsetX]*s__; sum_ += (long)tableDataHi[offsetX1]*s_0; sum_ += (long)tableDataHi[offsetX2]*s_1; sum_ += (long)tableDataHi[offsetX3]*s_2; long sum0 = (long)tableDataHi[offsetX]*s0_; sum0 += (long)tableDataHi[offsetX1]*s00; sum0 += (long)tableDataHi[offsetX2]*s01; sum0 += (long)tableDataHi[offsetX3]*s02; long sum1 = (long)tableDataHi[offsetX]*s1_; sum1 += (long)tableDataHi[offsetX1]*s10; sum1 += (long)tableDataHi[offsetX2]*s11; sum1 += (long)tableDataHi[offsetX3]*s12; long sum2 = (long)tableDataHi[offsetX]*s2_; sum2 += (long)tableDataHi[offsetX1]*s20; sum2 += (long)tableDataHi[offsetX2]*s21; sum2 += (long)tableDataHi[offsetX3]*s22; // Intermediate rounding sum_ = (sum_ + round) >> precisionBits; sum0 = (sum0 + round) >> precisionBits; sum1 = (sum1 + round) >> precisionBits; sum2 = (sum2 + round) >> precisionBits; // Interpolate in Y int offsetY = (int)(4*yfrac); long sum = (long)tableDataVi[offsetY]*sum_; sum += (long)tableDataVi[offsetY + 1]*sum0; sum += (long)tableDataVi[offsetY + 2]*sum1; sum += (long)tableDataVi[offsetY + 3]*sum2; s = (int)((sum + round) >> precisionBits); dstData[dstPixelOffset] = s; dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } private void floatLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); float dstDataArrays[][] = dst.getFloatDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); float srcDataArrays[][] = src.getFloatDataArrays(); int bandOffsets[] = src.getBandOffsets(); int dstOffset = 0; int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; int xfrac, yfrac; float s__, s_0, s_1, s_2; float s0_, s00, s01, s02; float s1_, s10, s11, s12; float s2_, s20, s21, s22; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { float dstData[] = dstDataArrays[k]; float srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow]; s_0 = srcData[posx + posylow]; s_1 = srcData[posxhigh + posylow]; s_2 = srcData[posxhigh2 + posylow]; s0_ = srcData[posxlow + posy]; s00 = srcData[posx + posy]; s01 = srcData[posxhigh + posy]; s02 = srcData[posxhigh2 + posy]; s1_ = srcData[posxlow + posyhigh]; s10 = srcData[posx + posyhigh]; s11 = srcData[posxhigh + posyhigh]; s12 = srcData[posxhigh2 + posyhigh]; s2_ = srcData[posxlow + posyhigh2]; s20 = srcData[posx + posyhigh2]; s21 = srcData[posxhigh + posyhigh2]; s22 = srcData[posxhigh2 + posyhigh2]; // Perform the bicubic interpolation // Interpolate in X int offsetX = (int)(4 * xfrac); int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; double sum_ = tableDataHf[offsetX]*s__; sum_ += tableDataHf[offsetX1]*s_0; sum_ += tableDataHf[offsetX2]*s_1; sum_ += tableDataHf[offsetX3]*s_2; double sum0 = tableDataHf[offsetX]*s0_; sum0 += tableDataHf[offsetX1]*s00; sum0 += tableDataHf[offsetX2]*s01; sum0 += tableDataHf[offsetX3]*s02; double sum1 = tableDataHf[offsetX]*s1_; sum1 += tableDataHf[offsetX1]*s10; sum1 += tableDataHf[offsetX2]*s11; sum1 += tableDataHf[offsetX3]*s12; double sum2 = tableDataHf[offsetX]*s2_; sum2 += tableDataHf[offsetX1]*s20; sum2 += tableDataHf[offsetX2]*s21; sum2 += tableDataHf[offsetX3]*s22; // Interpolate in Y int offsetY = (int)(4 * yfrac); double sum = tableDataVf[offsetY]*sum_; sum += tableDataVf[offsetY + 1]*sum0; sum += tableDataVf[offsetY + 2]*sum1; sum += tableDataVf[offsetY + 3]*sum2; if (sum > Float.MAX_VALUE) { sum = Float.MAX_VALUE; } else if (sum < -Float.MAX_VALUE) { sum = -Float.MAX_VALUE; } dstData[dstPixelOffset] = (float)sum; dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } private void doubleLoop(RasterAccessor src, Rectangle destRect, RasterAccessor dst, int xpos[], int ypos[], int xfracvalues[], int yfracvalues[]) { int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int dwidth = destRect.width; int dheight = destRect.height; int dnumBands = dst.getNumBands(); double dstDataArrays[][] = dst.getDoubleDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); double srcDataArrays[][] = src.getDoubleDataArrays(); int bandOffsets[] = src.getBandOffsets(); int dstOffset = 0; int posy, posylow, posyhigh, posyhigh2; int posx, posxlow, posxhigh, posxhigh2; double s__, s_0, s_1, s_2; double s0_, s00, s01, s02; double s1_, s10, s11, s12; double s2_, s20, s21, s22; double s; int xfrac, yfrac; // Putting band loop outside for (int k = 0; k < dnumBands; k++) { double dstData[] = dstDataArrays[k]; double srcData[] = srcDataArrays[k]; int dstScanlineOffset = dstBandOffsets[k]; int bandOffset = bandOffsets[k]; for (int j = 0; j < dheight; j++) { int dstPixelOffset = dstScanlineOffset; yfrac = yfracvalues[j]; posy = ypos[j] + bandOffset; posylow = posy - srcScanlineStride; posyhigh = posy + srcScanlineStride; posyhigh2 = posyhigh + srcScanlineStride; for (int i = 0; i < dwidth; i++) { xfrac = xfracvalues[i]; posx = xpos[i]; posxlow = posx - srcPixelStride; posxhigh = posx + srcPixelStride; posxhigh2 = posxhigh + srcPixelStride; // Get the sixteen surrounding pixel values s__ = srcData[posxlow + posylow]; s_0 = srcData[posx + posylow]; s_1 = srcData[posxhigh + posylow]; s_2 = srcData[posxhigh2 + posylow]; s0_ = srcData[posxlow + posy]; s00 = srcData[posx + posy]; s01 = srcData[posxhigh + posy]; s02 = srcData[posxhigh2 + posy]; s1_ = srcData[posxlow + posyhigh]; s10 = srcData[posx + posyhigh]; s11 = srcData[posxhigh + posyhigh]; s12 = srcData[posxhigh2 + posyhigh]; s2_ = srcData[posxlow + posyhigh2]; s20 = srcData[posx + posyhigh2]; s21 = srcData[posxhigh + posyhigh2]; s22 = srcData[posxhigh2 + posyhigh2]; // Perform the bicubic interpolation // Interpolate in X int offsetX = (int)(4 * xfrac); int offsetX1 = offsetX + 1; int offsetX2 = offsetX + 2; int offsetX3 = offsetX + 3; double sum_ = tableDataHd[offsetX]*s__; sum_ += tableDataHd[offsetX1]*s_0; sum_ += tableDataHd[offsetX2]*s_1; sum_ += tableDataHd[offsetX3]*s_2; double sum0 = tableDataHd[offsetX]*s0_; sum0 += tableDataHd[offsetX1]*s00; sum0 += tableDataHd[offsetX2]*s01; sum0 += tableDataHd[offsetX3]*s02; double sum1 = tableDataHd[offsetX]*s1_; sum1 += tableDataHd[offsetX1]*s10; sum1 += tableDataHd[offsetX2]*s11; sum1 += tableDataHd[offsetX3]*s12; double sum2 = tableDataHd[offsetX]*s2_; sum2 += tableDataHd[offsetX1]*s20; sum2 += tableDataHd[offsetX2]*s21; sum2 += tableDataHd[offsetX3]*s22; // Interpolate in Y int offsetY = (int)(4 * yfrac); s = tableDataVd[offsetY]*sum_; s += tableDataVd[offsetY + 1]*sum0; s += tableDataVd[offsetY + 2]*sum1; s += tableDataVd[offsetY + 3]*sum2; dstData[dstPixelOffset] = s; dstPixelOffset += dstPixelStride; } dstScanlineOffset += dstScanlineStride; } } } private synchronized void initTableDataI() { if (tableDataHi == null || tableDataVi == null) { tableDataHi = interpTable.getHorizontalTableData(); tableDataVi = interpTable.getVerticalTableData(); } } private synchronized void initTableDataF() { if (tableDataHf == null || tableDataVf == null) { tableDataHf = interpTable.getHorizontalTableDataFloat(); tableDataVf = interpTable.getVerticalTableDataFloat(); } } private synchronized void initTableDataD() { if (tableDataHd == null || tableDataVd == null) { tableDataHd = interpTable.getHorizontalTableDataDouble(); tableDataVd = interpTable.getVerticalTableDataDouble(); } } // public static OpImage createTestImage(OpImageTester oit) { // Interpolation interp = // Interpolation.getInstance(Interpolation.INTERP_BICUBIC); // return new ScaleBicubicOpImage(oit.getSource(), null, null, // new ImageLayout(oit.getSource()), // 2.5F, 2.5F, 0.0F, 0.0F, // interp); // } // public static void main(String args[]) { // String classname = "org.eclipse.imagen.media.opimage.ScaleBicubicOpImage"; // OpImageTester.performDiagnostics(classname,args); // System.exit(1); // System.out.println("ScaleOpImage Test"); // ImageLayout layout; // OpImage src, dst; // Rectangle rect = new Rectangle(2, 2, 5, 5); // InterpolationBicubic interp = new InterpolationBicubic(8); // System.out.println("1. PixelInterleaved short 3-band"); // layout = OpImageTester.createImageLayout(0, 0, 200, 200, 0, 0, // 64, 64, DataBuffer.TYPE_SHORT, // 3, false); // src = OpImageTester.createRandomOpImage(layout); // dst = new ScaleBicubicOpImage(src, null, null, null, // 2.0F, 2.0F, 0.0F, 0.0F, interp); // OpImageTester.testOpImage(dst, rect); // OpImageTester.timeOpImage(dst, 10); // System.out.println("2. PixelInterleaved ushort 3-band"); // layout = OpImageTester.createImageLayout(0, 0, 512, 512, 0, 0, // 200, 200, // DataBuffer.TYPE_USHORT, // 3, false); // src = OpImageTester.createRandomOpImage(layout); // dst = new ScaleBicubicOpImage(src, null, null, null, // 2.0F, 2.0F, 0.0F, 0.0F, interp); // OpImageTester.testOpImage(dst, rect); // OpImageTester.timeOpImage(dst, 10); // } }
33.163194
79
0.625406
8f919efbaa6e5c618402b2bbf3b9f8ef480a6b12
721
package com.kiwigrid.k8s.helm.tasks; import java.io.File; import com.kiwigrid.k8s.helm.HelmPlugin; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.OutputFiles; import org.gradle.api.tasks.TaskAction; /** * created on 28.03.18. * * @author Jörg Eichhorn {@literal <[email protected]>} */ public class HelmInitTask extends AbstractHelmTask { @TaskAction public void helmInit() { HelmPlugin.helmExec(getProject(), this, "init", "--client-only"); } @OutputDirectory public File getTaskOutput() { // we use the plugin directory as output because nobody messes with it return new File(super.getHelmHomeDirectory(), "plugins"); } }
24.862069
72
0.750347
cbd4ca9e75379078fab72d0a7a7bd76dd9924510
3,207
/* * Copyright (c) 2018, ITINordic * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package zw.org.mohcc.dhis.email; import zw.org.mohcc.dhis.email.EmailClient; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Rule; import zw.org.mohcc.dhis.JUnitSoftAssertions; /** * * @author cliffordc */ public class EmailClientTest { private Map<String, Object> sentEmail; @Rule public final JUnitSoftAssertions softly = new JUnitSoftAssertions(); public EmailClientTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { sentEmail = new HashMap<>(); } @After public void tearDown() { } /** * Test of sendEmail method, of class EmailClient. */ @Test public void testSendEmail() { System.out.println("sendEmail"); String from = "[email protected]"; String msg = "hello world"; String subject = "hello"; String[] toEmails = new String[]{"[email protected]", "[email protected]"}; EmailClient instance = new EmailClientImpl(); instance.sendMessage(from, toEmails, subject, msg); softly.assertThat(sentEmail) .containsKeys("from", "subject", "message", "recipients") .containsValues(from, subject, msg, toEmails); } public class EmailClientImpl implements EmailClient { @Override public void sendMessage(String from, String[] recipients, String subject, String message) { sentEmail.put("from", from); sentEmail.put("subject", subject); sentEmail.put("message", message); sentEmail.put("recipients", recipients); } } }
32.07
99
0.692548
a454fd5c0bdf0efb1fa6201f52a73b077abf9a69
613
package org.maxur.ddd.service; import org.maxur.ddd.domain.User; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import java.util.List; /** * @author myunusov * @version 1.0 * @since <pre>28.01.2016</pre> */ public interface UserDao { void insert(User user); void delete(String id); void update(User user); void changePassword(String id, String password); User findById(String id); List<User> findAll(); Integer findCountByTeam(String id); }
19.15625
52
0.714519
6d7a32d0597412bd48974dd25215861d7027d499
39,071
package com.telecominfraproject.wlan.alarm; 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 java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.telecominfraproject.wlan.alarm.models.Alarm; import com.telecominfraproject.wlan.alarm.models.AlarmCode; import com.telecominfraproject.wlan.alarm.models.AlarmCounts; import com.telecominfraproject.wlan.alarm.models.AlarmDetails; import com.telecominfraproject.wlan.cloudeventdispatcher.CloudEventDispatcherEmpty; import com.telecominfraproject.wlan.core.model.equipment.EquipmentType; import com.telecominfraproject.wlan.core.model.pagination.ColumnAndSort; import com.telecominfraproject.wlan.core.model.pagination.PaginationContext; import com.telecominfraproject.wlan.core.model.pagination.PaginationResponse; import com.telecominfraproject.wlan.core.model.pagination.SortOrder; import com.telecominfraproject.wlan.datastore.exceptions.DsConcurrentModificationException; import com.telecominfraproject.wlan.datastore.exceptions.DsEntityNotFoundException; import com.telecominfraproject.wlan.equipment.EquipmentServiceLocal; import com.telecominfraproject.wlan.equipment.datastore.inmemory.EquipmentDatastoreInMemory; import com.telecominfraproject.wlan.equipment.models.Equipment; import com.telecominfraproject.wlan.remote.tests.BaseRemoteTest; import com.telecominfraproject.wlan.status.models.StatusCode; /** * @author dtoptygin * */ @RunWith(SpringRunner.class) @ActiveProfiles(profiles = { "integration_test", "no_ssl","http_digest_auth","rest-template-single-user-per-service-digest-auth", }) //NOTE: these profiles will be ADDED to the list of active profiles @Import(value = { EquipmentServiceLocal.class, EquipmentDatastoreInMemory.class, CloudEventDispatcherEmpty.class }) public class AlarmServiceRemoteTest extends BaseRemoteTest { @Autowired AlarmServiceRemote remoteInterface; @Autowired EquipmentServiceLocal equipmentServicelocal; @Before public void urlSetup(){ configureBaseUrl("tip.wlan.alarmServiceBaseUrl"); } @Test public void testCRUD() { Alarm alarm = createAlarmObject(); //create Alarm created = remoteInterface.create(alarm); assertNotNull(created); assertEquals(alarm.getCustomerId(), created.getCustomerId()); assertEquals(alarm.getEquipmentId(), created.getEquipmentId()); assertEquals(alarm.getAlarmCode(), created.getAlarmCode()); assertEquals(alarm.getCreatedTimestamp(), created.getCreatedTimestamp()); assertNotNull(created.getDetails()); assertEquals(alarm.getDetails(), created.getDetails()); // update created.setScopeId("scope_updated"); Alarm updated = remoteInterface.update(created); assertNotNull(updated); assertEquals(created.getScopeId(), updated.getScopeId()); while(updated.getLastModifiedTimestamp() == created.getLastModifiedTimestamp()) { //update again to make the timestamps different created.setScopeId(created.getScopeId()+"_updated_1"); updated = remoteInterface.update(created); } //UPDATE test - fail because of concurrent modification exception try{ Alarm modelConcurrentUpdate = created.clone(); modelConcurrentUpdate.setScopeId("not important"); remoteInterface.update(modelConcurrentUpdate); fail("failed to detect concurrent modification"); }catch (DsConcurrentModificationException e) { // expected it } //retrieve Alarm retrieved = remoteInterface.getOrNull(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); assertNotNull(retrieved); assertEquals(retrieved.getLastModifiedTimestamp(), updated.getLastModifiedTimestamp()); //retrieve non-existent assertNull(remoteInterface.getOrNull(-1, -1, AlarmCode.AssocFailure, -1)); //delete retrieved = remoteInterface.delete(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); assertNotNull(retrieved); retrieved = remoteInterface.getOrNull(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); assertNull(retrieved); //delete non-existent try { remoteInterface.delete(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); fail("delete non-existing record"); }catch(DsEntityNotFoundException e ){ //expected it } //update non-existent try { remoteInterface.update(updated); fail("update non-existing record"); }catch(DsEntityNotFoundException e ){ //expected it } } @Test public void testGetAllForEquipment() { Set<Alarm> createdSet = new HashSet<>(); Set<Alarm> createdTestSet = new HashSet<>(); int customerId = getNextCustomerId(); long pastTimestamp = 0; //Create test Alarms for (int i = 0; i < 10; i++) { Alarm alarm = createAlarmObject(); alarm.setScopeId("test_" + i); alarm.setCustomerId(customerId); if(i == 8) { //create one record for the time of 10 sec ago alarm.setCreatedTimestamp(alarm.getCreatedTimestamp() - 10000); pastTimestamp = alarm.getCreatedTimestamp(); } Alarm ret = remoteInterface.create(alarm); // Only keep track of half of the created ones for testing if (i % 2 == 0) { createdTestSet.add(ret.clone()); } else { createdSet.add(ret.clone()); } } // Use only the IDs from the test set to retrieve records. Set<Long> testSetIds = new HashSet<>(); for (Alarm c : createdTestSet) { testSetIds.add(c.getEquipmentId()); } assertEquals(5, testSetIds.size()); List<Alarm> alarmsRetrievedByIdSet = remoteInterface.get(customerId, testSetIds, Collections.singleton(AlarmCode.AccessPointIsUnreachable)); assertEquals(5, alarmsRetrievedByIdSet.size()); for (Alarm c : alarmsRetrievedByIdSet) { assertTrue(createdTestSet.contains(c)); } // Make sure the alarms from the non-test set are not in the list for (Alarm c : alarmsRetrievedByIdSet) { assertTrue(!createdSet.contains(c)); } List<Alarm> alarmsRetrievedByNullAlarmCodeSet = remoteInterface.get(customerId, testSetIds, null); Collections.sort(alarmsRetrievedByIdSet); Collections.sort(alarmsRetrievedByNullAlarmCodeSet); assertEquals(alarmsRetrievedByIdSet, alarmsRetrievedByNullAlarmCodeSet); List<Alarm> alarmsRetrievedByManyAlarmCodeSet = remoteInterface.get(customerId, testSetIds, new HashSet<AlarmCode>(Arrays.asList(AlarmCode.AccessPointIsUnreachable, AlarmCode.AssocFailure))); Collections.sort(alarmsRetrievedByManyAlarmCodeSet); assertEquals(alarmsRetrievedByIdSet, alarmsRetrievedByManyAlarmCodeSet); try { remoteInterface.get(customerId, null, null); fail("equipmentIds must not be null"); } catch (IllegalArgumentException e) { //expected it } try { remoteInterface.get(customerId, Collections.emptySet(), null); fail("equipmentIds must not be empty"); } catch (IllegalArgumentException e) { //expected it } //test retrieve after specified time stamp List<Alarm> alarmsRetrievedAfterTs = remoteInterface.get(customerId, testSetIds, null, pastTimestamp + 10 ); assertEquals(4, alarmsRetrievedAfterTs.size()); alarmsRetrievedAfterTs.forEach(c -> assertTrue(createdTestSet.contains(c)) ); // Clean up after test for (Alarm c : createdSet) { remoteInterface.delete(c.getCustomerId(), c.getEquipmentId()); } for (Alarm c : createdTestSet) { remoteInterface.delete(c.getCustomerId(), c.getEquipmentId()); } } @Test public void testAlarmPagination() { //create 100 Alarms Alarm mdl; int customerId_1 = getNextCustomerId(); int customerId_2 = getNextCustomerId(); int apNameIdx = 0; Set<Long> equipmentIds = new HashSet<>(); Set<AlarmCode> alarmCodes = new HashSet<>(Arrays.asList(AlarmCode.AccessPointIsUnreachable, AlarmCode.AssocFailure)); long pastTimestamp = 0; for(int i = 0; i< 50; i++){ mdl = createAlarmObject(); mdl.setCustomerId(customerId_1); mdl.setScopeId("qr_"+apNameIdx); equipmentIds.add(mdl.getEquipmentId()); if(i == 8) { //create one record for the time of 10 sec ago mdl.setCreatedTimestamp(mdl.getCreatedTimestamp() - 10000); pastTimestamp = mdl.getCreatedTimestamp(); } if (i < 20) { mdl.setAcknowledged(true); } else { mdl.setAcknowledged(false); } apNameIdx++; remoteInterface.create(mdl); } for(int i = 0; i< 50; i++){ mdl = createAlarmObject(); mdl.setCustomerId(customerId_2); mdl.setScopeId("qr_"+apNameIdx); apNameIdx++; remoteInterface.create(mdl); } //paginate over Alarms List<ColumnAndSort> sortBy = new ArrayList<>(); sortBy.addAll(Arrays.asList(new ColumnAndSort("equipmentId"))); //get active alarms for all equipment and all alarmCodes for the customer since the beginning of time PaginationContext<Alarm> context = new PaginationContext<>(10); PaginationResponse<Alarm> page1 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, context); PaginationResponse<Alarm> page2 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page1.getContext()); PaginationResponse<Alarm> page3 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page2.getContext()); PaginationResponse<Alarm> page4 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page3.getContext()); PaginationResponse<Alarm> page5 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page4.getContext()); PaginationResponse<Alarm> page6 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page5.getContext()); PaginationResponse<Alarm> page7 = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, sortBy, page6.getContext()); //verify returned pages assertEquals(10, page1.getItems().size()); assertEquals(10, page2.getItems().size()); assertEquals(10, page3.getItems().size()); assertEquals(10, page4.getItems().size()); assertEquals(10, page5.getItems().size()); page1.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page2.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page3.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page4.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page5.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); assertEquals(0, page6.getItems().size()); assertEquals(0, page7.getItems().size()); assertFalse(page1.getContext().isLastPage()); assertFalse(page2.getContext().isLastPage()); assertFalse(page3.getContext().isLastPage()); assertFalse(page4.getContext().isLastPage()); assertFalse(page5.getContext().isLastPage()); assertTrue(page6.getContext().isLastPage()); assertTrue(page7.getContext().isLastPage()); List<String> expectedPage3Strings = new ArrayList< >(Arrays.asList(new String[]{"qr_20", "qr_21", "qr_22", "qr_23", "qr_24", "qr_25", "qr_26", "qr_27", "qr_28", "qr_29" })); List<String> actualPage3Strings = new ArrayList<>(); page3.getItems().stream().forEach( ce -> actualPage3Strings.add(ce.getScopeId()) ); assertEquals(expectedPage3Strings, actualPage3Strings); // testing Acknowledged filter (alarm_by_acknowledged) PaginationResponse<Alarm> page1Acknowledged = remoteInterface.getForCustomer(customerId_1, null, null, -1, true, sortBy, context); PaginationResponse<Alarm> page2Acknowledged = remoteInterface.getForCustomer(customerId_1, null, null, -1, true, sortBy, page1Acknowledged.getContext()); PaginationResponse<Alarm> page3Acknowledged = remoteInterface.getForCustomer(customerId_1, null, null, -1, true, sortBy, page2Acknowledged.getContext()); PaginationResponse<Alarm> page4Acknowledged = remoteInterface.getForCustomer(customerId_1, null, null, -1, true, sortBy, page3Acknowledged.getContext()); //verify returned pages assertEquals(10, page1Acknowledged.getItems().size()); assertEquals(10, page2Acknowledged.getItems().size()); assertEquals(0, page3Acknowledged.getItems().size()); assertEquals(0, page4Acknowledged.getItems().size()); // testing Acknowledged filter with equipmentIds (alarm_by_acknowledged_equipmentId) PaginationResponse<Alarm> page1AcknowledgedAndEquipment = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, -1, true, sortBy, context); PaginationResponse<Alarm> page2AcknowledgedAndEquipment = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, -1, true, sortBy, page1AcknowledgedAndEquipment.getContext()); PaginationResponse<Alarm> page3AcknowledgedAndEquipment = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, -1, true, sortBy, page2AcknowledgedAndEquipment.getContext()); PaginationResponse<Alarm> page4AcknowledgedAndEquipment = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, -1, true, sortBy, page3AcknowledgedAndEquipment.getContext()); page1AcknowledgedAndEquipment.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page2AcknowledgedAndEquipment.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page1AcknowledgedAndEquipment.getItems().forEach(e -> assertTrue(equipmentIds.contains(e.getEquipmentId()))); page2AcknowledgedAndEquipment.getItems().forEach(e -> assertTrue(equipmentIds.contains(e.getEquipmentId()))); assertTrue(page3AcknowledgedAndEquipment.getContext().isLastPage()); assertTrue(page4AcknowledgedAndEquipment.getContext().isLastPage()); // testing Acknowledged filter with alarmCodes (alarm_by_acknowledged_alarmCode) PaginationResponse<Alarm> page1AcknowledgedAndAlarmCode = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, -1, true, sortBy, context); PaginationResponse<Alarm> page2AcknowledgedAndAlarmCode = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, -1, true, sortBy, page1AcknowledgedAndAlarmCode.getContext()); PaginationResponse<Alarm> page3AcknowledgedAndAlarmCode = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, -1, true, sortBy, page2AcknowledgedAndAlarmCode.getContext()); PaginationResponse<Alarm> page4AcknowledgedAndAlarmCode = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, -1, true, sortBy, page3AcknowledgedAndAlarmCode.getContext()); page1AcknowledgedAndAlarmCode.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page2AcknowledgedAndAlarmCode.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page1AcknowledgedAndAlarmCode.getItems().forEach(e -> assertEquals(AlarmCode.AccessPointIsUnreachable, e.getAlarmCode())); page2AcknowledgedAndAlarmCode.getItems().forEach(e -> assertEquals(AlarmCode.AccessPointIsUnreachable, e.getAlarmCode())); assertTrue(page3AcknowledgedAndAlarmCode.getContext().isLastPage()); assertTrue(page4AcknowledgedAndAlarmCode.getContext().isLastPage()); // testing Acknowledged filter with failure alarm code (no alarms initialized with failure code, should return empty page) PaginationResponse<Alarm> page1AcknowledgedAndAlarmCodeFailure = remoteInterface.getForCustomer(customerId_1, equipmentIds, Collections.singleton(AlarmCode.AssocFailure), -1, true, sortBy, context); assertTrue(page1AcknowledgedAndAlarmCodeFailure.getContext().isLastPage()); long checkTimestamp = pastTimestamp; // testing Acknowledged filter with timestamp (alarm_by_acknowledged_timestamp) PaginationResponse<Alarm> page1AcknowledgedAndTimestamp = remoteInterface.getForCustomer(customerId_1, null, null, pastTimestamp, true, sortBy, context); PaginationResponse<Alarm> page2AcknowledgedAndTimestamp = remoteInterface.getForCustomer(customerId_1, null, null, pastTimestamp, true, sortBy, page1AcknowledgedAndTimestamp.getContext()); PaginationResponse<Alarm> page3AcknowledgedAndTimestamp = remoteInterface.getForCustomer(customerId_1, null, null, pastTimestamp, true, sortBy, page2AcknowledgedAndTimestamp.getContext()); PaginationResponse<Alarm> page4AcknowledgedAndTimestamp = remoteInterface.getForCustomer(customerId_1, null, null, pastTimestamp, true, sortBy, page3AcknowledgedAndTimestamp.getContext()); assertEquals(10, page1AcknowledgedAndTimestamp.getItems().size()); assertEquals(9, page2AcknowledgedAndTimestamp.getItems().size()); assertEquals(0, page3AcknowledgedAndTimestamp.getItems().size()); assertEquals(0, page4AcknowledgedAndTimestamp.getItems().size()); page1AcknowledgedAndTimestamp.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page2AcknowledgedAndTimestamp.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page1AcknowledgedAndTimestamp.getItems().forEach(e -> assertTrue(e.getCreatedTimestamp() > checkTimestamp)); page2AcknowledgedAndTimestamp.getItems().forEach(e -> assertTrue(e.getCreatedTimestamp() > checkTimestamp)); assertTrue(page3AcknowledgedAndTimestamp.getContext().isLastPage()); assertTrue(page4AcknowledgedAndTimestamp.getContext().isLastPage()); // testing Acknowledged with equipmentId and timestamp // With timestamp, alarmCodes will be set to AlarmCode.validValues, so these calls will be equivalent to having all filters included. // Because all filters are included, the alarm_by_acknowledged will be used instead of alarm_by_acknowledged_timestamp PaginationResponse<Alarm> page1AcknowledgedEquipmentIdAndTimestamp = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, pastTimestamp, true, sortBy, context); PaginationResponse<Alarm> page2AcknowledgedEquipmentIdAndTimestamp = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, pastTimestamp, true, sortBy, page1AcknowledgedEquipmentIdAndTimestamp.getContext()); PaginationResponse<Alarm> page3AcknowledgedEquipmentIdAndTimestamp = remoteInterface.getForCustomer(customerId_1, equipmentIds, null, pastTimestamp, true, sortBy, page2AcknowledgedEquipmentIdAndTimestamp.getContext()); assertEquals(10, page1AcknowledgedEquipmentIdAndTimestamp.getItems().size()); assertEquals(9, page2AcknowledgedEquipmentIdAndTimestamp.getItems().size()); assertEquals(0, page3AcknowledgedEquipmentIdAndTimestamp.getItems().size()); page1AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page2AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertEquals(true, e.isAcknowledged()) ); page1AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertTrue(equipmentIds.contains(e.getEquipmentId()))); page2AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertTrue(equipmentIds.contains(e.getEquipmentId()))); page1AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertTrue(e.getCreatedTimestamp() > checkTimestamp)); page2AcknowledgedEquipmentIdAndTimestamp.getItems().forEach(e -> assertTrue(e.getCreatedTimestamp() > checkTimestamp)); assertTrue(page3AcknowledgedEquipmentIdAndTimestamp.getContext().isLastPage()); //test first page of the results with empty sort order -> default sort order (by Id ascending) PaginationResponse<Alarm> page1EmptySort = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, Collections.emptyList(), context); assertEquals(10, page1EmptySort.getItems().size()); List<String> expectedPage1EmptySortStrings = new ArrayList<>(Arrays.asList(new String[]{"qr_0", "qr_1", "qr_2", "qr_3", "qr_4", "qr_5", "qr_6", "qr_7", "qr_8", "qr_9" })); List<String> actualPage1EmptySortStrings = new ArrayList<>(); page1EmptySort.getItems().stream().forEach( ce -> actualPage1EmptySortStrings.add(ce.getScopeId()) ); assertEquals(expectedPage1EmptySortStrings, actualPage1EmptySortStrings); //test first page of the results with null sort order -> default sort order (by Id ascending) PaginationResponse<Alarm> page1NullSort = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, null, context); assertEquals(10, page1NullSort.getItems().size()); List<String> expectedPage1NullSortStrings = new ArrayList<>(Arrays.asList(new String[]{"qr_0", "qr_1", "qr_2", "qr_3", "qr_4", "qr_5", "qr_6", "qr_7", "qr_8", "qr_9" })); List<String> actualPage1NullSortStrings = new ArrayList<>(); page1NullSort.getItems().stream().forEach( ce -> actualPage1NullSortStrings.add(ce.getScopeId()) ); assertEquals(expectedPage1NullSortStrings, actualPage1NullSortStrings); //test first page of the results with sort descending order by a equipmentId property PaginationResponse<Alarm> page1SingleSortDesc = remoteInterface.getForCustomer(customerId_1, null, null, -1, null, Collections.singletonList(new ColumnAndSort("equipmentId", SortOrder.desc)), context); assertEquals(10, page1SingleSortDesc.getItems().size()); List<String> expectedPage1SingleSortDescStrings = new ArrayList< >(Arrays.asList(new String[]{"qr_49", "qr_48", "qr_47", "qr_46", "qr_45", "qr_44", "qr_43", "qr_42", "qr_41", "qr_40" })); List<String> actualPage1SingleSortDescStrings = new ArrayList<>(); page1SingleSortDesc.getItems().stream().forEach( ce -> actualPage1SingleSortDescStrings.add(ce.getScopeId()) ); assertEquals(expectedPage1SingleSortDescStrings, actualPage1SingleSortDescStrings); //test with explicit list of equipmentIds and explicit list of AlarmCodes long createdAfterTs = pastTimestamp + 10; context = new PaginationContext<>(10); page1 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, context); page2 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page1.getContext()); page3 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page2.getContext()); page4 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page3.getContext()); page5 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page4.getContext()); page6 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page5.getContext()); page7 = remoteInterface.getForCustomer(customerId_1, equipmentIds, alarmCodes, createdAfterTs, null, sortBy, page6.getContext()); //verify returned pages assertEquals(10, page1.getItems().size()); assertEquals(10, page2.getItems().size()); assertEquals(10, page3.getItems().size()); assertEquals(10, page4.getItems().size()); assertEquals(9, page5.getItems().size()); assertEquals(0, page6.getItems().size()); page1.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page2.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page3.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page4.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); page5.getItems().forEach(e -> assertEquals(customerId_1, e.getCustomerId()) ); //test with explicit list of equipmentIds of one element and explicit list of AlarmCodes of one element context = new PaginationContext<>(10); page1 = remoteInterface.getForCustomer(customerId_1, Collections.singleton(equipmentIds.iterator().next()), Collections.singleton(AlarmCode.AccessPointIsUnreachable), -1, null, sortBy, context); assertEquals(1, page1.getItems().size()); } @Test public void testAlarmAcknowledgedPaginationWithUpdate() { Alarm alarm = createAlarmObject(); //create Alarm created = remoteInterface.create(alarm); assertNotNull(created); assertEquals(alarm.getCustomerId(), created.getCustomerId()); assertEquals(alarm.getEquipmentId(), created.getEquipmentId()); assertEquals(alarm.getAlarmCode(), created.getAlarmCode()); assertEquals(alarm.getCreatedTimestamp(), created.getCreatedTimestamp()); assertNotNull(created.getDetails()); assertEquals(alarm.getDetails(), created.getDetails()); List<ColumnAndSort> sortBy = new ArrayList<>(); sortBy.addAll(Arrays.asList(new ColumnAndSort("equipmentId"))); PaginationContext<Alarm> context = new PaginationContext<>(10); PaginationResponse<Alarm> page1CheckFalse = remoteInterface.getForCustomer(created.getCustomerId(), null, null, -1, false, sortBy, context); assertEquals(1, page1CheckFalse.getItems().size()); page1CheckFalse.getItems().forEach(e -> assertFalse(e.isAcknowledged())); PaginationResponse<Alarm> page1CheckTrue = remoteInterface.getForCustomer(created.getCustomerId(), null, null, -1, true, sortBy, context); assertEquals(0, page1CheckTrue.getItems().size()); // update created.setAcknowledged(true); Alarm updated = remoteInterface.update(created); assertNotNull(updated); assertTrue(updated.isAcknowledged()); page1CheckFalse = remoteInterface.getForCustomer(created.getCustomerId(), null, null, -1, false, sortBy, context); assertEquals(0, page1CheckFalse.getItems().size()); page1CheckTrue = remoteInterface.getForCustomer(created.getCustomerId(), null, null, -1, true, sortBy, context); assertEquals(1, page1CheckTrue.getItems().size()); page1CheckTrue.getItems().forEach(e -> assertTrue(e.isAcknowledged())); //delete created = remoteInterface.delete(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); assertNotNull(created); created = remoteInterface.getOrNull(created.getCustomerId(), created.getEquipmentId(), created.getAlarmCode(), created.getCreatedTimestamp()); assertNull(created); } @Test public void testAlarmCountsRetrieval() { //create some Alarms Alarm mdl; final int customerId_1 = getNextCustomerId(); final int customerId_2 = getNextCustomerId(); final long equipmentId_1 = createEquipmentObject(customerId_1).getId(); int apNameIdx = 0; Set<Long> equipmentIds = new HashSet<>(); Set<Long> equipmentIds_CPUUtilization = new HashSet<>(); Set<Long> equipmentIds_AccessPointIsUnreachable = new HashSet<>(); for(int i = 0; i< 50; i++){ mdl = createAlarmObject(customerId_1, createEquipmentObject(customerId_1).getId()); mdl.setEquipmentId(createEquipmentObject(customerId_1).getId()); mdl.setScopeId("qr_"+apNameIdx); if((i%2) == 0) { mdl.setAlarmCode(AlarmCode.CPUUtilization); mdl.setAcknowledged(true); equipmentIds_CPUUtilization.add(mdl.getEquipmentId()); } else { equipmentIds_AccessPointIsUnreachable.add(mdl.getEquipmentId()); } equipmentIds.add(mdl.getEquipmentId()); apNameIdx++; remoteInterface.create(mdl); } mdl = createAlarmObject(customerId_1, equipmentId_1); mdl.setCustomerId(customerId_1); mdl.setAlarmCode(AlarmCode.GenericError); remoteInterface.create(mdl); for(int i = 0; i< 50; i++){ mdl = createAlarmObject(customerId_2, createEquipmentObject(customerId_2).getId()); mdl.setScopeId("qr_"+apNameIdx); mdl.setAcknowledged(false); mdl.setAlarmCode(AlarmCode.GenericError); apNameIdx++; remoteInterface.create(mdl); } Set<AlarmCode> alarmCodes = new HashSet<>(Arrays.asList(AlarmCode.AccessPointIsUnreachable, AlarmCode.GenericError, AlarmCode.CPUUtilization)); AlarmCounts alarmCounts = remoteInterface.getAlarmCounts(customerId_1, equipmentIds, alarmCodes, null); assertEquals(0, alarmCounts.getCounter(0, AlarmCode.GenericError)); assertEquals(25, alarmCounts.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(25, alarmCounts.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(25, alarmCounts.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(25, alarmCounts.getSeverityCounter(StatusCode.error)); equipmentIds_CPUUtilization.forEach(eqId -> assertEquals(1, alarmCounts.getCounter(eqId, AlarmCode.CPUUtilization))); equipmentIds_AccessPointIsUnreachable.forEach(eqId -> assertEquals(1, alarmCounts.getCounter(eqId, AlarmCode.AccessPointIsUnreachable)) ); AlarmCounts alarmCounts_noEq = remoteInterface.getAlarmCounts(customerId_1, null, alarmCodes, null); assertEquals(1, alarmCounts_noEq.getCounter(0, AlarmCode.GenericError)); assertEquals(25, alarmCounts_noEq.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(25, alarmCounts_noEq.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(25, alarmCounts_noEq.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(26, alarmCounts_noEq.getSeverityCounter(StatusCode.error)); assertTrue(alarmCounts_noEq.getCountsPerEquipmentIdMap().isEmpty()); assertEquals(3, alarmCounts_noEq.getTotalCountsPerAlarmCodeMap().size()); AlarmCounts alarmCounts_noEq_1code = remoteInterface.getAlarmCounts(customerId_1, null, Collections.singleton(AlarmCode.CPUUtilization), null); assertEquals(0, alarmCounts_noEq_1code.getCounter(0, AlarmCode.GenericError)); assertEquals(25, alarmCounts_noEq_1code.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(0, alarmCounts_noEq_1code.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(25, alarmCounts_noEq_1code.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(0, alarmCounts_noEq_1code.getSeverityCounter(StatusCode.error)); assertTrue(alarmCounts_noEq_1code.getCountsPerEquipmentIdMap().isEmpty()); assertEquals(1, alarmCounts_noEq_1code.getTotalCountsPerAlarmCodeMap().size()); AlarmCounts alarmCounts_acknowledgedT = remoteInterface.getAlarmCounts(customerId_1, null, Collections.singleton(AlarmCode.CPUUtilization), true); assertTrue(alarmCounts_acknowledgedT.getAcknowledged()); assertEquals(0, alarmCounts_acknowledgedT.getCounter(0, AlarmCode.GenericError)); assertEquals(25, alarmCounts_acknowledgedT.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(0, alarmCounts_acknowledgedT.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(25, alarmCounts_acknowledgedT.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(0, alarmCounts_acknowledgedT.getSeverityCounter(StatusCode.error)); assertTrue(alarmCounts_acknowledgedT.getCountsPerEquipmentIdMap().isEmpty()); assertEquals(1, alarmCounts_acknowledgedT.getTotalCountsPerAlarmCodeMap().size()); AlarmCounts alarmCounts_acknowledgedF = remoteInterface.getAlarmCounts(customerId_1, null, Collections.singleton(AlarmCode.CPUUtilization), false); assertFalse(alarmCounts_acknowledgedF.getAcknowledged()); assertEquals(0, alarmCounts_acknowledgedF.getCounter(0, AlarmCode.GenericError)); assertEquals(0, alarmCounts_acknowledgedF.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(0, alarmCounts_acknowledgedF.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(0, alarmCounts_acknowledgedF.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(0, alarmCounts_acknowledgedF.getSeverityCounter(StatusCode.error)); assertTrue(alarmCounts_acknowledgedF.getCountsPerEquipmentIdMap().isEmpty()); assertEquals(0, alarmCounts_acknowledgedF.getTotalCountsPerAlarmCodeMap().size()); AlarmCounts alarmCounts_acknowledgedF2 = remoteInterface.getAlarmCounts(customerId_2, null, Collections.singleton(AlarmCode.GenericError), false); assertFalse(alarmCounts_acknowledgedF2.getAcknowledged()); assertEquals(50, alarmCounts_acknowledgedF2.getCounter(0, AlarmCode.GenericError)); assertEquals(0, alarmCounts_acknowledgedF2.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(0, alarmCounts_acknowledgedF2.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(0, alarmCounts_acknowledgedF2.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(50, alarmCounts_acknowledgedF2.getSeverityCounter(StatusCode.error)); assertTrue(alarmCounts_acknowledgedF2.getCountsPerEquipmentIdMap().isEmpty()); assertEquals(1, alarmCounts_acknowledgedF2.getTotalCountsPerAlarmCodeMap().size()); AlarmCounts alarmCounts_1Eq_1code = remoteInterface.getAlarmCounts(customerId_1, Collections.singleton(equipmentIds.iterator().next()), Collections.singleton(AlarmCode.CPUUtilization), null); assertEquals(0, alarmCounts_1Eq_1code.getCounter(0, AlarmCode.GenericError)); assertEquals(1, alarmCounts_1Eq_1code.getCounter(equipmentIds.iterator().next(), AlarmCode.CPUUtilization)); assertEquals(1, alarmCounts_1Eq_1code.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(0, alarmCounts_1Eq_1code.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(1, alarmCounts_1Eq_1code.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(0, alarmCounts_1Eq_1code.getSeverityCounter(StatusCode.error)); assertEquals(1, alarmCounts_1Eq_1code.getCountsPerEquipmentIdMap().size()); assertEquals(1, alarmCounts_1Eq_1code.getTotalCountsPerAlarmCodeMap().size()); } @Test public void testAlarmCountsForSingleEquipment() { //create some Alarms Alarm mdl; int customerId = getNextCustomerId(); long equipmentId = getNextEquipmentId(); mdl = createAlarmObject(); mdl.setCustomerId(customerId); mdl.setEquipmentId(equipmentId); mdl.setAlarmCode(AlarmCode.CPUUtilization); remoteInterface.create(mdl); mdl.setAlarmCode(AlarmCode.AccessPointIsUnreachable); remoteInterface.create(mdl); Set<AlarmCode> alarmCodes = new HashSet<>(Arrays.asList(AlarmCode.AccessPointIsUnreachable, AlarmCode.GenericError, AlarmCode.CPUUtilization)); AlarmCounts alarmCounts = remoteInterface.getAlarmCounts(customerId, Collections.singleton(equipmentId), alarmCodes, null); assertEquals(0, alarmCounts.getCounter(0, AlarmCode.GenericError)); assertEquals(1, alarmCounts.getCounter(0, AlarmCode.CPUUtilization)); assertEquals(1, alarmCounts.getCounter(0, AlarmCode.AccessPointIsUnreachable)); assertEquals(2, alarmCounts.getCounter(equipmentId, null)); assertEquals(1, alarmCounts.getSeverityCounter(StatusCode.requiresAttention)); assertEquals(1, alarmCounts.getSeverityCounter(StatusCode.error)); //clean up after the test remoteInterface.delete(customerId, equipmentId); } private Alarm createAlarmObject() { int customerId = getNextCustomerId(); return createAlarmObject(customerId, createEquipmentObject(customerId).getId()); } private Alarm createAlarmObject(int customerId, long equipmentId) { Alarm result = new Alarm(); result.setCustomerId(customerId); result.setAlarmCode(AlarmCode.AccessPointIsUnreachable); result.setCreatedTimestamp(System.currentTimeMillis()); result.setEquipmentId(equipmentId); result.setScopeId("test-scope-" + result.getEquipmentId()); AlarmDetails details = new AlarmDetails(); details.setMessage("test-details-" + result.getEquipmentId()); result.setDetails(details ); return result; } private Equipment createEquipmentObject(int customerId) { Equipment equipment = new Equipment(); equipment.setName("testName"); equipment.setInventoryId("test-inv"); equipment.setEquipmentType(EquipmentType.AP); equipment.setCustomerId(customerId); return equipmentServicelocal.create(equipment); } }
56.136494
225
0.714648
d90c16e999ff85a463c4010063bd7bd7825c15b4
1,962
package com.italankin.lnch.model.repository.store.json; import com.italankin.lnch.model.descriptor.Descriptor; import com.italankin.lnch.model.descriptor.impl.AppDescriptor; import com.italankin.lnch.model.descriptor.impl.DeepShortcutDescriptor; import com.italankin.lnch.model.descriptor.impl.GroupDescriptor; import com.italankin.lnch.model.descriptor.impl.IntentDescriptor; import com.italankin.lnch.model.descriptor.impl.PinnedShortcutDescriptor; import com.italankin.lnch.model.repository.store.json.model.AppDescriptorJson; import com.italankin.lnch.model.repository.store.json.model.DeepShortcutDescriptorJson; import com.italankin.lnch.model.repository.store.json.model.DescriptorJson; import com.italankin.lnch.model.repository.store.json.model.GroupDescriptorJson; import com.italankin.lnch.model.repository.store.json.model.IntentDescriptorJson; import com.italankin.lnch.model.repository.store.json.model.PinnedShortcutDescriptorJson; class DescriptorJsonConverter { Descriptor fromJson(DescriptorJson descriptorJson) { return descriptorJson.toDescriptor(); } DescriptorJson toJson(Descriptor descriptor) { if (descriptor instanceof AppDescriptor) { return new AppDescriptorJson((AppDescriptor) descriptor); } if (descriptor instanceof GroupDescriptor) { return new GroupDescriptorJson((GroupDescriptor) descriptor); } if (descriptor instanceof DeepShortcutDescriptor) { return new DeepShortcutDescriptorJson((DeepShortcutDescriptor) descriptor); } if (descriptor instanceof PinnedShortcutDescriptor) { return new PinnedShortcutDescriptorJson((PinnedShortcutDescriptor) descriptor); } if (descriptor instanceof IntentDescriptor) { return new IntentDescriptorJson((IntentDescriptor) descriptor); } throw new IllegalArgumentException("Unknown Descriptor: " + descriptor); } }
47.853659
91
0.77421
e4e4e3e8440ddbc1cc8aafc02584f1b2225d3408
351
package swt6.spring.bl; import sun.rmi.runtime.Log; import swt6.spring.domain.Employee; import swt6.spring.domain.Issue; import swt6.spring.domain.LogbookEntry; import java.util.List; public interface LogbookEntryManager extends BaseManager<LogbookEntry, Long> { List<LogbookEntry> findAllByEmployeeAndIssue(Employee employee, Issue issue); }
27
81
0.811966
9050427b600ae46dee1522c1a389a50e4e4ad54d
349
package org.albianj.mvc.service; import org.albianj.mvc.config.AlbianHttpConfigurtion; import org.albianj.service.IAlbianService; /** * Created by xuhaifeng on 16/12/6. */ public interface IAlbianMVCConfigurtionService extends IAlbianService { String Name ="AlbianMvcConfigurtionService"; AlbianHttpConfigurtion getHttpConfigurtion(); }
26.846154
71
0.802292
8a8f3f9dfff6abcbe33920cc57a70d8ef54f9fde
17,797
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.databasemanagement.model; /** * The details of a datafile. * <br/> * Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields * that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in * the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called * {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take * {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__} * (since the constructor cannot distinguish explicit {@code null} from unset {@code null}). **/ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20201101") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = Datafile.Builder.class) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) @lombok.Builder(builderClassName = "Builder", toBuilder = true) public class Datafile { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("name") private String name; public Builder name(String name) { this.name = name; this.__explicitlySet__.add("name"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("status") private Status status; public Builder status(Status status) { this.status = status; this.__explicitlySet__.add("status"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("onlineStatus") private OnlineStatus onlineStatus; public Builder onlineStatus(OnlineStatus onlineStatus) { this.onlineStatus = onlineStatus; this.__explicitlySet__.add("onlineStatus"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("isAutoExtensible") private Boolean isAutoExtensible; public Builder isAutoExtensible(Boolean isAutoExtensible) { this.isAutoExtensible = isAutoExtensible; this.__explicitlySet__.add("isAutoExtensible"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("lostWriteProtect") private LostWriteProtect lostWriteProtect; public Builder lostWriteProtect(LostWriteProtect lostWriteProtect) { this.lostWriteProtect = lostWriteProtect; this.__explicitlySet__.add("lostWriteProtect"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("shared") private Shared shared; public Builder shared(Shared shared) { this.shared = shared; this.__explicitlySet__.add("shared"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("instanceId") private java.math.BigDecimal instanceId; public Builder instanceId(java.math.BigDecimal instanceId) { this.instanceId = instanceId; this.__explicitlySet__.add("instanceId"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("maxSizeKB") private java.math.BigDecimal maxSizeKB; public Builder maxSizeKB(java.math.BigDecimal maxSizeKB) { this.maxSizeKB = maxSizeKB; this.__explicitlySet__.add("maxSizeKB"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("allocatedSizeKB") private java.math.BigDecimal allocatedSizeKB; public Builder allocatedSizeKB(java.math.BigDecimal allocatedSizeKB) { this.allocatedSizeKB = allocatedSizeKB; this.__explicitlySet__.add("allocatedSizeKB"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("userSizeKB") private java.math.BigDecimal userSizeKB; public Builder userSizeKB(java.math.BigDecimal userSizeKB) { this.userSizeKB = userSizeKB; this.__explicitlySet__.add("userSizeKB"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("incrementBy") private java.math.BigDecimal incrementBy; public Builder incrementBy(java.math.BigDecimal incrementBy) { this.incrementBy = incrementBy; this.__explicitlySet__.add("incrementBy"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("freeSpaceKB") private java.math.BigDecimal freeSpaceKB; public Builder freeSpaceKB(java.math.BigDecimal freeSpaceKB) { this.freeSpaceKB = freeSpaceKB; this.__explicitlySet__.add("freeSpaceKB"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("usedSpaceKB") private java.math.BigDecimal usedSpaceKB; public Builder usedSpaceKB(java.math.BigDecimal usedSpaceKB) { this.usedSpaceKB = usedSpaceKB; this.__explicitlySet__.add("usedSpaceKB"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("usedPercentAvailable") private Double usedPercentAvailable; public Builder usedPercentAvailable(Double usedPercentAvailable) { this.usedPercentAvailable = usedPercentAvailable; this.__explicitlySet__.add("usedPercentAvailable"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("usedPercentAllocated") private Double usedPercentAllocated; public Builder usedPercentAllocated(Double usedPercentAllocated) { this.usedPercentAllocated = usedPercentAllocated; this.__explicitlySet__.add("usedPercentAllocated"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); public Datafile build() { Datafile __instance__ = new Datafile( name, status, onlineStatus, isAutoExtensible, lostWriteProtect, shared, instanceId, maxSizeKB, allocatedSizeKB, userSizeKB, incrementBy, freeSpaceKB, usedSpaceKB, usedPercentAvailable, usedPercentAllocated); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(Datafile o) { Builder copiedBuilder = name(o.getName()) .status(o.getStatus()) .onlineStatus(o.getOnlineStatus()) .isAutoExtensible(o.getIsAutoExtensible()) .lostWriteProtect(o.getLostWriteProtect()) .shared(o.getShared()) .instanceId(o.getInstanceId()) .maxSizeKB(o.getMaxSizeKB()) .allocatedSizeKB(o.getAllocatedSizeKB()) .userSizeKB(o.getUserSizeKB()) .incrementBy(o.getIncrementBy()) .freeSpaceKB(o.getFreeSpaceKB()) .usedSpaceKB(o.getUsedSpaceKB()) .usedPercentAvailable(o.getUsedPercentAvailable()) .usedPercentAllocated(o.getUsedPercentAllocated()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The filename (including the path) of the datafile or tempfile. **/ @com.fasterxml.jackson.annotation.JsonProperty("name") String name; /** * The status of the file. INVALID status is used when the file number is not in use, for example, a file in a tablespace that was dropped. **/ @lombok.extern.slf4j.Slf4j public enum Status { Available("AVAILABLE"), Invalid("INVALID"), Offline("OFFLINE"), Online("ONLINE"), Unknown("UNKNOWN"), /** * This value is used if a service returns a value for this enum that is not recognized by this * version of the SDK. */ UnknownEnumValue(null); private final String value; private static java.util.Map<String, Status> map; static { map = new java.util.HashMap<>(); for (Status v : Status.values()) { if (v != UnknownEnumValue) { map.put(v.getValue(), v); } } } Status(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static Status create(String key) { if (map.containsKey(key)) { return map.get(key); } LOG.warn( "Received unknown value '{}' for enum 'Status', returning UnknownEnumValue", key); return UnknownEnumValue; } }; /** * The status of the file. INVALID status is used when the file number is not in use, for example, a file in a tablespace that was dropped. **/ @com.fasterxml.jackson.annotation.JsonProperty("status") Status status; /** * The online status of the file. **/ @lombok.extern.slf4j.Slf4j public enum OnlineStatus { Sysoff("SYSOFF"), System("SYSTEM"), Offline("OFFLINE"), Online("ONLINE"), Recover("RECOVER"), /** * This value is used if a service returns a value for this enum that is not recognized by this * version of the SDK. */ UnknownEnumValue(null); private final String value; private static java.util.Map<String, OnlineStatus> map; static { map = new java.util.HashMap<>(); for (OnlineStatus v : OnlineStatus.values()) { if (v != UnknownEnumValue) { map.put(v.getValue(), v); } } } OnlineStatus(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static OnlineStatus create(String key) { if (map.containsKey(key)) { return map.get(key); } LOG.warn( "Received unknown value '{}' for enum 'OnlineStatus', returning UnknownEnumValue", key); return UnknownEnumValue; } }; /** * The online status of the file. **/ @com.fasterxml.jackson.annotation.JsonProperty("onlineStatus") OnlineStatus onlineStatus; /** * Indicates whether the datafile is auto-extensible. **/ @com.fasterxml.jackson.annotation.JsonProperty("isAutoExtensible") Boolean isAutoExtensible; /** * The lost write protection status of the file. **/ @lombok.extern.slf4j.Slf4j public enum LostWriteProtect { Enabled("ENABLED"), ProtectOff("PROTECT_OFF"), Suspend("SUSPEND"), /** * This value is used if a service returns a value for this enum that is not recognized by this * version of the SDK. */ UnknownEnumValue(null); private final String value; private static java.util.Map<String, LostWriteProtect> map; static { map = new java.util.HashMap<>(); for (LostWriteProtect v : LostWriteProtect.values()) { if (v != UnknownEnumValue) { map.put(v.getValue(), v); } } } LostWriteProtect(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static LostWriteProtect create(String key) { if (map.containsKey(key)) { return map.get(key); } LOG.warn( "Received unknown value '{}' for enum 'LostWriteProtect', returning UnknownEnumValue", key); return UnknownEnumValue; } }; /** * The lost write protection status of the file. **/ @com.fasterxml.jackson.annotation.JsonProperty("lostWriteProtect") LostWriteProtect lostWriteProtect; /** * Type of tablespace this file belongs to. If it's for a shared tablespace, for a local temporary tablespace for RIM (read-only) instances, or for local temporary tablespace for all instance types. **/ @lombok.extern.slf4j.Slf4j public enum Shared { Shared("SHARED"), LocalForRim("LOCAL_FOR_RIM"), LocalForAll("LOCAL_FOR_ALL"), /** * This value is used if a service returns a value for this enum that is not recognized by this * version of the SDK. */ UnknownEnumValue(null); private final String value; private static java.util.Map<String, Shared> map; static { map = new java.util.HashMap<>(); for (Shared v : Shared.values()) { if (v != UnknownEnumValue) { map.put(v.getValue(), v); } } } Shared(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator public static Shared create(String key) { if (map.containsKey(key)) { return map.get(key); } LOG.warn( "Received unknown value '{}' for enum 'Shared', returning UnknownEnumValue", key); return UnknownEnumValue; } }; /** * Type of tablespace this file belongs to. If it's for a shared tablespace, for a local temporary tablespace for RIM (read-only) instances, or for local temporary tablespace for all instance types. **/ @com.fasterxml.jackson.annotation.JsonProperty("shared") Shared shared; /** * Instance ID of the instance to which the temp file belongs. This column has a NULL value for temp files that belong to shared tablespaces. **/ @com.fasterxml.jackson.annotation.JsonProperty("instanceId") java.math.BigDecimal instanceId; /** * The maximum file size in KB. **/ @com.fasterxml.jackson.annotation.JsonProperty("maxSizeKB") java.math.BigDecimal maxSizeKB; /** * The allocated file size in KB. **/ @com.fasterxml.jackson.annotation.JsonProperty("allocatedSizeKB") java.math.BigDecimal allocatedSizeKB; /** * The size of the file available for user data in KB. The actual size of the file minus the USER_BYTES value is used to store file-related metadata. **/ @com.fasterxml.jackson.annotation.JsonProperty("userSizeKB") java.math.BigDecimal userSizeKB; /** * The number of blocks used as auto-extension increment. **/ @com.fasterxml.jackson.annotation.JsonProperty("incrementBy") java.math.BigDecimal incrementBy; /** * The free space available in the datafile in KB. **/ @com.fasterxml.jackson.annotation.JsonProperty("freeSpaceKB") java.math.BigDecimal freeSpaceKB; /** * The total space used in the datafile in KB. **/ @com.fasterxml.jackson.annotation.JsonProperty("usedSpaceKB") java.math.BigDecimal usedSpaceKB; /** * The percentage of used space out of the maximum available space in the file. **/ @com.fasterxml.jackson.annotation.JsonProperty("usedPercentAvailable") Double usedPercentAvailable; /** * The percentage of used space out of the total allocated space in the file. **/ @com.fasterxml.jackson.annotation.JsonProperty("usedPercentAllocated") Double usedPercentAllocated; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); }
35.665331
246
0.600719
11247b9c819cfb4241c8cccf910c1fbbe552fca1
6,149
package com.github.rschmitt.dynamicobject.internal; import com.github.rschmitt.dynamicobject.Cached; import com.github.rschmitt.dynamicobject.DynamicObject; import com.github.rschmitt.dynamicobject.Key; import com.github.rschmitt.dynamicobject.Meta; import com.github.rschmitt.dynamicobject.Required; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.cachedRead; import static java.util.stream.Collectors.toSet; class Reflection { static <D extends DynamicObject<D>> Collection<Method> requiredFields(Class<D> type) { Collection<Method> fields = fieldGetters(type); return fields.stream().filter(Reflection::isRequired).collect(toSet()); } static <D extends DynamicObject<D>> Set<Object> cachedKeys(Class<D> type) { return Arrays.stream(type.getMethods()) .flatMap(Reflection::getCachedKeysForMethod) .collect(toSet()); } private static Stream<Object> getCachedKeysForMethod(Method method) { if (isGetter(method)) { if (method.getAnnotation(Cached.class) != null) { return Stream.of(getKeyForGetter(method)); } else { return Stream.empty(); } } else if (isBuilder(method)) { if (method.getAnnotation(Cached.class) != null) { return Stream.of(getKeyForBuilder(method)); } else { // If the getter has an annotation it'll contribute it directly return Stream.empty(); } } else { return Stream.empty(); } } static <D extends DynamicObject<D>> Collection<Method> fieldGetters(Class<D> type) { Collection<Method> ret = new LinkedHashSet<>(); for (Method method : type.getDeclaredMethods()) if (isGetter(method)) ret.add(method); return ret; } private static boolean isBuilder(Method method) { return method.getParameterCount() == 1 && method.getDeclaringClass().isAssignableFrom(method.getReturnType()); } private static boolean isAnyGetter(Method method) { return method.getParameterCount() == 0 && !method.isDefault() && !method.isSynthetic() && (method.getModifiers() & Modifier.STATIC) == 0 && method.getReturnType() != Void.TYPE; } private static boolean isGetter(Method method) { return isAnyGetter(method) && !isMetadataGetter(method); } static boolean isMetadataGetter(Method method) { return isAnyGetter(method) && hasAnnotation(method, Meta.class); } static boolean isRequired(Method getter) { return hasAnnotation(getter, Required.class); } private static boolean hasAnnotation(Method method, Class<? extends Annotation> ann) { List<Annotation> annotations = Arrays.asList(method.getAnnotations()); for (Annotation annotation : annotations) if (annotation.annotationType().equals(ann)) return true; return false; } static boolean isMetadataBuilder(Method method) { if (method.getParameterCount() != 1) return false; if (hasAnnotation(method, Meta.class)) return true; if (hasAnnotation(method, Key.class)) return false; Method correspondingGetter = getCorrespondingGetter(method); return hasAnnotation(correspondingGetter, Meta.class); } static Object getKeyForGetter(Method method) { Key annotation = getMethodAnnotation(method, Key.class); if (annotation == null) return stringToKey(":" + method.getName()); else return stringToKey(annotation.value()); } private static Object stringToKey(String keyName) { if (keyName.charAt(0) == ':') return cachedRead(keyName); else return keyName; } @SuppressWarnings("unchecked") private static <T> T getMethodAnnotation(Method method, Class<T> annotationType) { for (Annotation annotation : method.getAnnotations()) if (annotation.annotationType().equals(annotationType)) return (T) annotation; return null; } static Object getKeyForBuilder(Method method) { Key annotation = getMethodAnnotation(method, Key.class); if (annotation == null) return getKeyForGetter(getCorrespondingGetter(method)); else return stringToKey(annotation.value()); } private static Method getCorrespondingGetter(Method builderMethod) { try { Class<?> type = builderMethod.getDeclaringClass(); Method correspondingGetter = type.getMethod(builderMethod.getName()); return correspondingGetter; } catch (NoSuchMethodException ex) { throw new IllegalStateException("Builder method " + builderMethod + " must have a corresponding getter method or a @Key annotation.", ex); } } static Class<?> getRawType(Type type) { if (type instanceof Class) return (Class<?>) type; else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return (Class<?>) parameterizedType.getRawType(); } else throw new UnsupportedOperationException(); } static Type getTypeArgument(Type type, int idx) { if (type instanceof Class) return Object.class; else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return parameterizedType.getActualTypeArguments()[idx]; } else throw new UnsupportedOperationException(); } }
37.266667
150
0.649699
8bc6eb6e80da08249955b19eecbc14542291e588
15,444
package com.intuit.service.dsl.evaluator; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import com.fasterxml.jackson.core.JsonProcessingException; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.intuit.dsl.service.Service; import com.intuit.service.dsl.AddBookServicePost; import com.intuit.service.dsl.AddBookServicePut; import com.intuit.service.dsl.BookByIdService; import com.intuit.service.dsl.BooksService; import com.intuit.service.dsl.JsonUtils; import com.intuit.service.dsl.evaluator.exceptions.ServiceEvaluatorException; import com.intuit.service.dsl.utils.TestUtil; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class ServiceEvaluatorTest { private static int WIREMOCK_PORT = 4060; private ServiceEvaluator serviceEvaluator; @Rule public WireMockRule wireMockRule = new WireMockRule(WIREMOCK_PORT); // consider using mockito to mock webclient @Before public void setup() { serviceEvaluator = makeServiceEvaluator(TestUtil.createServiceConfiguration(TestUtil.TIMEOUT, WIREMOCK_PORT)); } @Test public void canEvaluateServiceNodeWithPostMethod() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/books"; stubFor(post(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); String serviceName = "addBooks"; final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePost.addBookDSL, serviceName); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePost.svcEvaluatorReq4Post, serviceName); // WHEN String result = serviceEvaluator .evaluate(serviceEvaluatorRequest) .get(); // THEN String requestBodyCriteria = "$[?(@.id == 'book-1' " + "&& @.name == 'The Book' " + "&& @.price == 100.00 " + ")]"; verify(exactly(1), postRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(matchingJsonPath(requestBodyCriteria))); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price"); } @Test public void canEvaluateServiceNodeWithPutMethod() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/books"; String serviceName = "addBooksPUT"; final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePut.addBookDSL, serviceName); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePut.svcEvaluatorReq4Put, serviceName); stubFor(put(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(serviceEvaluatorRequest).get(); // THEN String requestBodyCriteria = "$[?(@.id == 'book-1' " + "&& @.name == 'The Book' " + "&& @.price == 100.00 " + ")]"; verify(exactly(1), putRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(matchingJsonPath(requestBodyCriteria))); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price"); } @Test public void canEvaluateServiceNodeWithGetMethod() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/books/book-1"; stubFor(get(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100, \"status\" : \"AVAILABLE\"}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReq4GetWithParam).get(); // THEN verify(exactly(1), getRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(absent())); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price", "status"); } @Test public void canEvaluateServiceNodeForGetMethodWithMultipleArgument() throws ExecutionException, InterruptedException, JsonProcessingException { // GIVEN String svcEndpoint = "/books/book-1"; stubFor(get(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100, \"status\" : \"AVAILABLE\"}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReq4GetWithParamMultiArg).get(); // THEN verify(exactly(1), getRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(absent())); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price", "status"); } @Test public void canEvaluateServiceNodeWithNoArgumentForGetMethod() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/books"; final Service service = TestUtil.getService("main/flow/service.service", BooksService.booksDSL, null); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePut.svcEvaluatorReq4Put, null); stubFor(get(urlPathMatching(svcEndpoint)) .withQueryParam("limit", equalTo("10")) .willReturn(aResponse() .withStatus(200) .withBody("[{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100, \"status\" : \"AVAILABLE\"}]") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(BooksService.svcEvaluatorReq4GETNoParam).get(); // THEN verify(exactly(1), getRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(absent())); List<Map<String, Object>> resultMap = JsonUtils.MAPPER.readValue(result, List.class); assertThat(resultMap).isNotNull(); } // @Test(expected = ServiceEvaluatorException.class) // public void cannotEvaluateWithInvalidDSLFile() { // // GIVEN // ServiceResourceLoader booksResourceLoader = TestUtil.createResourceLoader("main/flow/invalidFileName.service", // BooksService.booksDSL, serviceConfiguration); // // // WHEN .. THEN throws exception // makeServiceEvaluator(BooksService.svcEvaluatorReq4InvalidDSL, // booksResourceLoader, "GraphQL.Query"); // } // @Test(expected = NullPointerException.class) // public void cannotCreateWithNoRequestType() { // // GIVEN // ServiceResourceLoader booksResourceLoader = TestUtil.createResourceLoader("main/flow/invalidFileName.service", // BooksService.booksDSL, serviceConfiguration); // // // when .. then throws exception // ServiceEvaluator.builder() // .serviceEvaluatorRequest(BooksService.svcEvaluatorReq4NoRequestTypeInSvcEvaluator) // .resourceLoader(booksResourceLoader) // .webClient(TestUtil.webClient) // .serviceId("TEST_SERVICE") // //.requestType(requestType) <-- this is ommited // .build(); // } @Test public void canEvaluateServiceNodeWithPostAndBodyAnnotation() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/books"; final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePost.addBookDSL, "addBooksWithBody"); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePost.svcEvaluatorReqBodyAnnotation, "addBooksWithBody"); stubFor(post(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(serviceEvaluatorRequest).get(); // THEN String requestBodyCriteria1 = "$.newBook[?(@.id == 'book-1' " + "&& @.name == 'The Book' " + ")]"; String requestBodyCriteria2 = "$[?(@.newBookId == 'book-1')]"; String requestBodyCriteria3 = "$.chapters[?(@ == 'Chapter-3')]"; String requestBodyCriteria4 = "$[?(@.price == 100.00)]"; String requestBodyCriteria5 = "$[?(@.isPublished == true)]"; String requestBodyCriteria6 = "$[?(@.isHardPrint == false)]"; String requestBodyCriteria7 = "$[?(@.author == null)]"; verify(exactly(1), postRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(matchingJsonPath(requestBodyCriteria1)) .withRequestBody(matchingJsonPath(requestBodyCriteria2)) .withRequestBody(matchingJsonPath(requestBodyCriteria3)) .withRequestBody(matchingJsonPath(requestBodyCriteria4)) .withRequestBody(matchingJsonPath(requestBodyCriteria5)) .withRequestBody(matchingJsonPath(requestBodyCriteria6)) .withRequestBody(matchingJsonPath(requestBodyCriteria7)) ); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price"); } @Test public void canEvaluateServiceNodeWithPostAndNoKeyBodyAnnotation() throws ExecutionException, InterruptedException, IOException { // GIVEN String svcEndpoint = "/custombody/nokey/books"; final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePost.addBookDSL, "addBooksNoKeyBody"); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePost.svcEvaluatorReqNoKeyBodyAnnotation, "addBooksNoKeyBody"); stubFor(post(urlPathMatching(svcEndpoint)) .willReturn(aResponse() .withStatus(200) .withBody("{\"id\": \"book-1\",\"name\": \"The Book\",\"price\": 100}") .withHeader("Content-Type", "application/json;charset=UTF-8"))); // WHEN String result = serviceEvaluator.evaluate(serviceEvaluatorRequest).get(); // THEN String requestBodyCriteria = "$[?(@.id == 'book-1' " + "&& @.name == 'The Book' " + ")]"; verify(exactly(1), postRequestedFor(urlPathMatching(svcEndpoint)) .withRequestBody(matchingJsonPath(requestBodyCriteria))); Map<String, Object> resultMap = JsonUtils.MAPPER.readValue(result, Map.class); assertThat(resultMap).containsOnlyKeys("id", "name", "price"); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedServiceNodeWithPostWithMultipleArguments() { // NOTE: Without using @Body, i.e default body construction, only 1 arg is supported for POST. // GIVEN final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePost.addBookDSL, "addBooks"); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePost.svcEvaluatorReq4PostWithMultiArg, "addBooks"); // WHEN serviceEvaluator.evaluate(serviceEvaluatorRequest); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedServiceNodeWithPutWithMultipleArguments() { // NOTE: Without using @Body, i.e default body construction, only 1 arg is supported for PUT. // GIVEN final Service service = TestUtil.getService("main/flow/service.service", AddBookServicePost.addBookDSL, "addBooksPUT"); ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil .createServiceEvaluatorRequest(service, AddBookServicePost.svcEvaluatorReq4PostWithMultiArg, "addBooksPUT"); // WHEN serviceEvaluator.evaluate(serviceEvaluatorRequest); } // // ToDo: Think about this case // // @Test(expected = NullPointerException.class) // public void evaluateFailedServiceNodeWithPutWithNoArgument() { // // GIVEN // // final Service service = TestUtil.getService("main/flow/service.service", // AddBookServicePut.addBookDSL, "addBooksPUT"); // ServiceEvaluatorRequest serviceEvaluatorRequest = TestUtil // .createServiceEvaluatorRequest(service, AddBookServicePut.svcEvaluatorReq4PutNoArg, "addBooksPUT"); // // // WHEN // serviceEvaluator.evaluate(serviceEvaluatorRequest); // } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedCannotCreateBodyNoKey4StringValue() { serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReqErrStringNokey); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedCannotCreateBodyNoKey4ArrayValue() { serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReqErrArrayNokey); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedPathParamExpressionNotString() { serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReqErrPathParamNotString); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedPathParamExpressionNull() { serviceEvaluator.evaluate(BookByIdService.svcEvaluatorReqErrPathParamNull); } @Test(expected = ServiceEvaluatorException.class) public void evaluateFailedNoServiceNode() { TestUtil.getService("main/flow/service.service", BookByIdService.bookByIdDSLErrNoServiceNode, null); } private static ServiceEvaluator makeServiceEvaluator( ServiceConfiguration serviceConfiguration ) { return ServiceEvaluator.builder() .serviceConfiguration(serviceConfiguration) .webClient(TestUtil.webClient) .build(); } }
42.662983
124
0.723582
c46ffcd25caab2ea37ae003f52ff1d8f050f0331
2,206
package cz.cuni.mff.xrg.odalic.api.rdf.values; import java.util.Set; import com.complexible.pinto.annotations.RdfProperty; import com.complexible.pinto.annotations.RdfsClass; import com.google.common.collect.ImmutableSet; import cz.cuni.mff.xrg.odalic.api.rdf.values.util.Annotations; import cz.cuni.mff.xrg.odalic.tasks.annotations.CellAnnotation; /** * <p> * Domain class {@link CellAnnotation} adapted for RDF serialization. * </p> * * @author Václav Brodec * */ @RdfsClass("http://odalic.eu/internal/CellAnnotation") public final class CellAnnotationValue { private Set<KnowledgeBaseEntityCandidateNavigableSetEntry> candidates; private Set<KnowledgeBaseEntityCandidateSetEntry> chosen; public CellAnnotationValue() { this.candidates = ImmutableSet.of(); this.chosen = ImmutableSet.of(); } public CellAnnotationValue(final CellAnnotation adaptee) { this.candidates = Annotations.toNavigableValues(adaptee.getCandidates()); this.chosen = Annotations.toValues(adaptee.getChosen()); } /** * @return the candidates */ @RdfProperty("http://odalic.eu/internal/CellAnnotation/candidates") public Set<KnowledgeBaseEntityCandidateNavigableSetEntry> getCandidates() { return this.candidates; } /** * @return the chosen */ @RdfProperty("http://odalic.eu/internal/CellAnnotation/chosen") public Set<KnowledgeBaseEntityCandidateSetEntry> getChosen() { return this.chosen; } /** * @param candidates the candidates to set */ public void setCandidates( final Set<? extends KnowledgeBaseEntityCandidateNavigableSetEntry> candidates) { this.candidates = Annotations.copyNavigableValues(candidates); } /** * @param chosen the chosen to set */ public void setChosen(final Set<? extends KnowledgeBaseEntityCandidateSetEntry> chosen) { this.chosen = Annotations.copyValues(chosen); } public CellAnnotation toCellAnnotation() { return new CellAnnotation(Annotations.toNavigableDomain(this.candidates), Annotations.toDomain(this.chosen)); } @Override public String toString() { return "CellAnnotationValue [candidates=" + this.candidates + ", chosen=" + this.chosen + "]"; } }
28.282051
98
0.740707
259ca73060478742e317ed374c8d6c5d4940a58f
4,965
package seedu.weme.logic.commands.memecommand; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.weme.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.weme.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.weme.logic.commands.CommandTestUtil.showMemeAtIndex; import static seedu.weme.testutil.TypicalIndexes.INDEX_FIRST; import static seedu.weme.testutil.TypicalIndexes.INDEX_SECOND; import static seedu.weme.testutil.TypicalWeme.getTypicalWeme; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.testfx.framework.junit5.ApplicationTest; import seedu.weme.commons.core.Messages; import seedu.weme.commons.core.index.Index; import seedu.weme.model.Model; import seedu.weme.model.ModelManager; import seedu.weme.model.UserPrefs; import seedu.weme.model.meme.Meme; import seedu.weme.testutil.MemeBuilder; /** * Contains integration tests (interaction with the Model, UndoCommand and RedoCommand) and unit tests for * {@code MemeArchiveCommand}. */ public class MemeArchiveCommandTest extends ApplicationTest { private Model model; @BeforeEach public void setup() { model = new ModelManager(getTypicalWeme(), new UserPrefs()); } @Test public void execute_validIndexUnfilteredList_success() { Meme memeToArchive = model.getFilteredMemeList().get(INDEX_FIRST.getZeroBased()); MemeArchiveCommand memeArchiveCommand = new MemeArchiveCommand(INDEX_FIRST); Meme archivedMeme = new MemeBuilder(memeToArchive).withIsArchived(true).build(); String expectedMessage = String.format(MemeArchiveCommand.MESSAGE_ARCHIVE_MEME_SUCCESS, memeToArchive); ModelManager expectedModel = new ModelManager(model.getWeme(), new UserPrefs()); expectedModel.setMeme(memeToArchive, archivedMeme); expectedModel.commitWeme(expectedMessage); assertCommandSuccess(memeArchiveCommand, model, expectedMessage, expectedModel); } @Test public void execute_invalidIndexUnfilteredList_throwsCommandException() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredMemeList().size() + 1); MemeArchiveCommand memeArchiveCommand = new MemeArchiveCommand(outOfBoundIndex); assertCommandFailure(memeArchiveCommand, model, Messages.MESSAGE_INVALID_MEME_DISPLAYED_INDEX); } @Test public void execute_validIndexFilteredList_success() { showMemeAtIndex(model, INDEX_FIRST); Meme memeToArchive = model.getFilteredMemeList().get(INDEX_FIRST.getZeroBased()); MemeArchiveCommand memeArchiveCommand = new MemeArchiveCommand(INDEX_FIRST); Meme archivedMeme = new MemeBuilder(memeToArchive).withIsArchived(true).build(); String expectedMessage = String.format(MemeArchiveCommand.MESSAGE_ARCHIVE_MEME_SUCCESS, memeToArchive); Model expectedModel = new ModelManager(model.getWeme(), new UserPrefs()); expectedModel.setMeme(memeToArchive, archivedMeme); expectedModel.commitWeme(expectedMessage); assertCommandSuccess(memeArchiveCommand, model, expectedMessage, expectedModel); } @Test public void execute_invalidIndexFilteredList_throwsCommandException() { showMemeAtIndex(model, INDEX_FIRST); Index outOfBoundIndex = INDEX_SECOND; // ensures that outOfBoundIndex is still in bounds of meme list assertTrue(outOfBoundIndex.getZeroBased() < model.getWeme().getMemeList().size()); MemeArchiveCommand memeArchiveCommand = new MemeArchiveCommand(outOfBoundIndex); assertCommandFailure(memeArchiveCommand, model, Messages.MESSAGE_INVALID_MEME_DISPLAYED_INDEX); } @Test public void execute_archivedMeme_throwsCommandException() { model.updateFilteredMemeList(Model.PREDICATE_SHOW_ALL_ARCHIVED_MEMES); MemeArchiveCommand memeArchiveCommand = new MemeArchiveCommand(INDEX_FIRST); assertCommandFailure(memeArchiveCommand, model, MemeArchiveCommand.MESSAGE_ALREADY_ARCHIVED); } @Test public void equals() { MemeArchiveCommand archiveFirstCommand = new MemeArchiveCommand(INDEX_FIRST); MemeArchiveCommand archiveSecondCommand = new MemeArchiveCommand(INDEX_SECOND); // same object -> returns true assertTrue(archiveFirstCommand.equals(archiveFirstCommand)); // same values -> returns true MemeArchiveCommand archiveFirstCommandCopy = new MemeArchiveCommand(INDEX_FIRST); assertTrue(archiveFirstCommand.equals(archiveFirstCommandCopy)); // different types -> returns false assertFalse(archiveFirstCommand.equals(1)); // null -> returns false assertFalse(archiveFirstCommand.equals(null)); // different meme -> returns false assertFalse(archiveFirstCommand.equals(archiveSecondCommand)); } }
41.033058
111
0.765156
a6d70e69cd7e66319f027d7484df0ce86075020e
7,483
package com.skeqi.mes.pojo.chenj.srm.rsp; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author ChenJ * @date 2021/7/1 * @Classname CSrmSendCommodityH * @Description ${Description} */ /** * 送货单头表 */ @ApiModel(value = "com-skeqi-pojo-chenj-CSrmSendCommodityH") public class CSrmSendCommodityHRspD { /** * 送货单号 */ @ApiModelProperty(value = "送货单号") private String deliveryNumber; /** * 送货单类型(1.标准送货单) */ @ApiModelProperty(value = "送货单类型(1.标准送货单)") private String typeOfDeliveryNote; /** * 发货日期 */ @ApiModelProperty(value = "发货日期") private String deliveryDate; /** * 预计到货日期 */ @ApiModelProperty(value = "预计到货日期") private String expectedDateOfArrival; /** * 收货地点 */ @ApiModelProperty(value = "收货地点") private String placeOfReceipt; /** * 发货地点 */ @ApiModelProperty(value = "发货地点") private String pointOfDeparture; /** * 收货组织 */ @ApiModelProperty(value = "收货组织") private String receivingOrganization; /** * 收货组织名称 */ @ApiModelProperty(value = "收货组织名称") private String receivingOrganizationName; /** * 供应商名称 */ @ApiModelProperty(value = "供应商名称") private String supplierName; /** * 客户 */ @ApiModelProperty(value = "客户") private String client; /** * 收货人 */ @ApiModelProperty(value = "收货人") private String consignee; /** * 供应商 */ @ApiModelProperty(value = "供应商编码") private String supplierCode; /** * 创建人 */ @ApiModelProperty(value = "创建人") private String creator; /** * 状态(1.新建2.待确认3.待发货4.待收货5.已完成) */ @ApiModelProperty(value = "状态(1.新建2.待确认3.待发货4.待收货5.已完成)") private String status; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private String createTime; /** * 修改时间 */ @ApiModelProperty(value = "修改时间") private String updateTime; /** * 物流单号 */ private String trackingNumber; /** * 物流公司信息 */ private String logisticsCompanyInformation; /** * 联系方式 */ private String contactWay; /** * 送货方式 ( 1.人工,2.物流) */ private Integer shippingMethod; public String getDeliveryNumber() { return deliveryNumber; } public void setDeliveryNumber(String deliveryNumber) { this.deliveryNumber = deliveryNumber; } public String getTypeOfDeliveryNote() { return typeOfDeliveryNote; } public void setTypeOfDeliveryNote(String typeOfDeliveryNote) { this.typeOfDeliveryNote = typeOfDeliveryNote; } public String getDeliveryDate() { return deliveryDate; } public void setDeliveryDate(String deliveryDate) { this.deliveryDate = deliveryDate; } public String getExpectedDateOfArrival() { return expectedDateOfArrival; } public void setExpectedDateOfArrival(String expectedDateOfArrival) { this.expectedDateOfArrival = expectedDateOfArrival; } public String getPlaceOfReceipt() { return placeOfReceipt; } public String getContactWay() { return contactWay; } public void setContactWay(String contactWay) { this.contactWay = contactWay; } public void setPlaceOfReceipt(String placeOfReceipt) { this.placeOfReceipt = placeOfReceipt; } public String getPointOfDeparture() { return pointOfDeparture; } public void setPointOfDeparture(String pointOfDeparture) { this.pointOfDeparture = pointOfDeparture; } public String getReceivingOrganization() { return receivingOrganization; } public String getSupplierName() { return supplierName; } public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public String getLogisticsCompanyInformation() { return logisticsCompanyInformation; } public void setLogisticsCompanyInformation(String logisticsCompanyInformation) { this.logisticsCompanyInformation = logisticsCompanyInformation; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public void setReceivingOrganization(String receivingOrganization) { this.receivingOrganization = receivingOrganization; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } public String getReceivingOrganizationName() { return receivingOrganizationName; } public void setReceivingOrganizationName(String receivingOrganizationName) { this.receivingOrganizationName = receivingOrganizationName; } public String getSupplierCode() { return supplierCode; } public void setSupplierCode(String supplierCode) { this.supplierCode = supplierCode; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public Integer getShippingMethod() { return shippingMethod; } public void setShippingMethod(Integer shippingMethod) { this.shippingMethod = shippingMethod; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "CSrmSendCommodityHRspD{" + "deliveryNumber='" + deliveryNumber + '\'' + ", typeOfDeliveryNote='" + typeOfDeliveryNote + '\'' + ", deliveryDate='" + deliveryDate + '\'' + ", expectedDateOfArrival='" + expectedDateOfArrival + '\'' + ", placeOfReceipt='" + placeOfReceipt + '\'' + ", pointOfDeparture='" + pointOfDeparture + '\'' + ", receivingOrganization='" + receivingOrganization + '\'' + ", receivingOrganizationName='" + receivingOrganizationName + '\'' + ", supplierName='" + supplierName + '\'' + ", client='" + client + '\'' + ", consignee='" + consignee + '\'' + ", supplierCode='" + supplierCode + '\'' + ", creator='" + creator + '\'' + ", status='" + status + '\'' + ", createTime='" + createTime + '\'' + ", updateTime='" + updateTime + '\'' + ", trackingNumber='" + trackingNumber + '\'' + ", logisticsCompanyInformation='" + logisticsCompanyInformation + '\'' + ", contactWay='" + contactWay + '\'' + ", shippingMethod=" + shippingMethod + '}'; } }
23.23913
88
0.601898
3c37162209974f24b9fe21e5dc2728d1e84a1fbd
5,844
package edu.cmu.oli.content.boundary.managers; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import edu.cmu.oli.content.AppUtils; import edu.cmu.oli.content.ResourceException; import edu.cmu.oli.content.controllers.LockController; import edu.cmu.oli.content.logging.Logging; import edu.cmu.oli.content.models.ResourceEditLock; import edu.cmu.oli.content.models.persistance.entities.ContentPackage; import edu.cmu.oli.content.models.persistance.entities.Resource; import edu.cmu.oli.content.models.persistance.entities.ResourceState; import edu.cmu.oli.content.security.AppSecurityContext; import edu.cmu.oli.content.security.AppSecurityController; import edu.cmu.oli.content.security.Scopes; import edu.cmu.oli.content.security.Secure; import org.slf4j.Logger; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.Arrays; import java.util.List; import static edu.cmu.oli.content.security.Roles.ADMIN; import static edu.cmu.oli.content.security.Roles.CONTENT_DEVELOPER; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; /** * @author Raphael Gachuhi */ @Stateless public class LockResourceManager { enum LockActions { AQUIRE, RELEASE, STATUS } @Inject @Logging Logger log; @PersistenceContext EntityManager em; @Inject @Secure AppSecurityController securityManager; @Inject LockController lockController; public JsonElement lock(AppSecurityContext session, String packageIdOrGuid, String resourceId, String action) { ContentPackage contentPackage = findContentPackage(packageIdOrGuid); securityManager.authorize(session, Arrays.asList(ADMIN, CONTENT_DEVELOPER), contentPackage.getGuid(), "name=" + contentPackage.getGuid(), Arrays.asList(Scopes.VIEW_MATERIAL_ACTION)); LockActions act; try { act = LockActions.valueOf(action.toUpperCase()); } catch (Exception ex) { String message = "Action not supported " + action; throw new ResourceException(BAD_REQUEST, null, message); } Resource resource = findContentResource(resourceId, contentPackage); switch (act) { case AQUIRE: ResourceEditLock resourceEditLock = lockController.aquire(session, resource.getGuid()); Gson gson = AppUtils.gsonBuilder().excludeFieldsWithoutExposeAnnotation().serializeNulls().create(); JsonElement lockJson = gson.toJsonTree(resourceEditLock); return lockJson; case RELEASE: return new JsonPrimitive(lockController.release(session, resource.getGuid())); case STATUS: return new JsonPrimitive(lockController.status(resource.getGuid())); default: String message = "Action not supported " + action; throw new ResourceException(BAD_REQUEST, null, message); } } private Resource findContentResource(String resourceId, ContentPackage contentPackage) { Resource resource = null; try { resource = em.find(Resource.class, resourceId); if (resource != null) { return resource; } TypedQuery<Resource> q = em.createNamedQuery("Resource.findByIdAndPackage", Resource.class) .setParameter("id", resourceId).setParameter("package", contentPackage); List<Resource> resultList = q.getResultList(); if (resultList.isEmpty() || resultList.get(0).getResourceState() == ResourceState.DELETED) { String message = "ContentResource not found " + resourceId; throw new ResourceException(Response.Status.NOT_FOUND, resourceId, message); } return resultList.get(0); } catch (IllegalArgumentException e) { String message = "Server Error while locating resource " + resourceId; log.error(message); throw new ResourceException(Response.Status.INTERNAL_SERVER_ERROR, resourceId, message); } } // packageIdentifier is db guid or packageId-version combo private ContentPackage findContentPackage(String packageIdOrGuid) { ContentPackage contentPackage = null; Boolean isIdAndVersion = packageIdOrGuid.contains("-"); try { if (isIdAndVersion) { String pkgId = packageIdOrGuid.substring(0, packageIdOrGuid.lastIndexOf("-")); String version = packageIdOrGuid.substring(packageIdOrGuid.lastIndexOf("-") + 1); TypedQuery<ContentPackage> q = em .createNamedQuery("ContentPackage.findByIdAndVersion", ContentPackage.class) .setParameter("id", pkgId).setParameter("version", version); contentPackage = q.getResultList().isEmpty() ? null : q.getResultList().get(0); } else { String packageGuid = packageIdOrGuid; contentPackage = em.find(ContentPackage.class, packageGuid); } if (contentPackage == null) { String message = "Error: package requested was not found " + packageIdOrGuid; log.error(message); throw new ResourceException(Response.Status.NOT_FOUND, packageIdOrGuid, message); } } catch (IllegalArgumentException e) { String message = "Server Error while locating package " + packageIdOrGuid; log.error(message); throw new ResourceException(Response.Status.INTERNAL_SERVER_ERROR, packageIdOrGuid, message); } return contentPackage; } }
41.446809
115
0.680185
2dec230caa1ce8f9558cebccafe3df7d6baee885
5,596
package weixin; import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.io.*; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpRequestUtil { private static final Logger LOG=Logger.getLogger(HttpRequestUtil.class); public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { TrustManager[] tm = {new MyX509TrustManager()}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (ConnectException ce) { } catch (Exception e) { } return jsonObject; } public static String sendPost(String url, Map<String, Object> params) { StringBuffer sb = new StringBuffer(); if (params != null) { for (Entry<String, Object> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } sb.substring(0, sb.length() - 1); } PrintWriter out = null; BufferedReader in = null; System.out.println("sb:"+sb); String result = ""; HttpURLConnection conn =null; try { URL realUrl = new URL(url); conn = (HttpURLConnection)realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8")); out.print(sb.toString()); out.flush(); in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } //result= new String(result.getBytes("GBK"),"UTF-8"); } catch (Exception e) { LOG.error(e); }finally { if (conn != null) { conn.disconnect(); } } return result; } public static String sendGet(String url, Map<String, Object> params) { StringBuffer sb = new StringBuffer(); if (params != null) { for (Entry<String, Object> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } sb.substring(0, sb.length() - 1); } String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + sb.toString(); URL realUrl = new URL(urlNameString); URLConnection connection = realUrl.openConnection(); //connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } in = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } //result= new String(result.getBytes("GBK"),"UTF-8"); } catch (Exception e) { LOG.error(e); result = e.getMessage().substring(0,100); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { LOG.error(e2); } } return result; } }
31.615819
98
0.604718
7d1e95e6daef8cac629f4847b82ade97bc1f71ee
8,650
package com.mridang.computer; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.google.android.apps.dashclock.api.ExtensionData; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.acra.ACRA; import org.apache.http.Header; import org.apache.http.entity.StringEntity; import java.io.IOException; import java.security.MessageDigest; /* * This class is the main class that provides the widget */ public class ComputerWidget extends ImprovedExtension { /** * The handler class that hides the notification after a few seconds */ private class HeartbeatHandler extends Handler { /** * Simple constructor to initialize the initial value of the previous */ public HeartbeatHandler(Looper looLooper) { super(looLooper); } /** * Handler method that that acts an and expiration checker that upon expiry simple hides the * dashclock notification. */ @Override public void handleMessage(Message msgMessage) { try { Log.d(getTag(), "User has been notified of logoff so hide message"); ExtensionData edtInformation = new ExtensionData(); edtInformation.visible(false); doUpdate(edtInformation); } catch (Exception e) { Log.e(ComputerWidget.this.getTag(), "Error hiding the notification", e); } } } /** * The instance of the manager of the notification services */ private static NotificationManager mgrNotifications; /** * The instance of the notification builder to rebuild the notification */ private static NotificationCompat.Builder notBuilder; /** * This is the instance of the thread that keeps track of connected clients */ private HeartbeatHandler hndWaiter; /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#getIntents() */ @Override protected IntentFilter getIntents() { IntentFilter itfIntents = new IntentFilter(); itfIntents.addAction("com.google.android.c2dm.intent.RECEIVE"); itfIntents.addCategory("com.mridang.computer"); return itfIntents; } /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#getTag() */ @Override protected String getTag() { return getClass().getSimpleName(); } /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#getUris() */ @Override protected String[] getUris() { return null; } /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#onInitialize(java.lang.Boolean) */ @Override protected void onInitialize(boolean booReconnect) { super.onInitialize(booReconnect); mgrNotifications = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notBuilder = new NotificationCompat.Builder(this); notBuilder = notBuilder.setSmallIcon(R.drawable.ic_dashclock); notBuilder = notBuilder.setOngoing(false); notBuilder = notBuilder.setShowWhen(true); notBuilder = notBuilder.setOnlyAlertOnce(false); notBuilder = notBuilder.setPriority(Integer.MAX_VALUE); notBuilder = notBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notBuilder = notBuilder.setCategory(NotificationCompat.CATEGORY_SERVICE); Looper.prepare(); hndWaiter = new HeartbeatHandler(Looper.myLooper()); Looper.loop(); } /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#onDestroy() */ @Override public void onDestroy() { mgrNotifications.cancel(115); super.onDestroy(); } /* * (non-Javadoc) * @see com.mridang.hardware.ImprovedExtension#onReceiveIntent(android.content.Context, android.content.Intent) */ @Override protected void onReceiveIntent(Context ctxContext, Intent ittIntent) { ExtensionData edtInformation = new ExtensionData(); try { Bundle bndBundle = ittIntent.getExtras(); String strUsername = bndBundle.getString("username").toLowerCase(); String strMachine = bndBundle.getString("machine"); notBuilder = notBuilder.setWhen(System.currentTimeMillis()); notBuilder = notBuilder.setContentTitle(strMachine); edtInformation.visible(true); edtInformation.expandedBody(strMachine); if (bndBundle.getString("event").equalsIgnoreCase("logon")) { Log.d(getTag(), strUsername + " logged on at " + strMachine); edtInformation.expandedTitle(getString(R.string.logon, strUsername)); notBuilder = notBuilder.setContentText(edtInformation.expandedTitle()); mgrNotifications.notify(115, notBuilder.build()); } else if (bndBundle.getString("event").equalsIgnoreCase("lock")) { Log.d(getTag(), strUsername + " locked the computer " + strMachine); edtInformation.expandedTitle(getString(R.string.lock, strUsername)); notBuilder = notBuilder.setContentText(edtInformation.expandedTitle()); mgrNotifications.notify(115, notBuilder.build()); } else if (bndBundle.getString("event").equalsIgnoreCase("unlock")) { Log.d(getTag(), strUsername + " unlocked the computer " + strMachine); edtInformation.expandedTitle(getString(R.string.unlock, strUsername)); notBuilder = notBuilder.setContentText(edtInformation.expandedTitle()); mgrNotifications.notify(115, notBuilder.build()); } else if (bndBundle.getString("event").equalsIgnoreCase("logoff")) { Log.d(getTag(), strUsername + " logged off at " + strMachine); edtInformation.expandedTitle(getString(R.string.logoff, strUsername)); notBuilder = notBuilder.setContentText(edtInformation.expandedTitle()); mgrNotifications.notify(115, notBuilder.build()); } else { Log.v(getTag(), strUsername + " is active on " + strMachine); edtInformation.expandedTitle(getString(R.string.active, strUsername)); } hndWaiter.removeMessages(1); hndWaiter.sendEmptyMessageDelayed(1, 120000); } catch (Exception e) { edtInformation.visible(false); Log.e(getTag(), "Encountered an error", e); ACRA.getErrorReporter().handleSilentException(e); } edtInformation.icon(R.drawable.ic_dashclock); doUpdate(edtInformation); } /* * @see * com.google.android.apps.dashclock.api.DashClockExtension#onUpdateData * (int) */ @Override protected void onUpdateData(int intReason) { setUpdateWhenScreenOn(true); Log.d(getTag(), "Checking if the widget is configured"); if (getString("hostname", "").isEmpty()) { Log.d(getTag(), "Hostname hasn't been configured"); Toast.makeText(getApplicationContext(), getString(R.string.unconfigured), Toast.LENGTH_LONG).show(); } else { try { String strToken = GoogleCloudMessaging.getInstance(getApplicationContext()).register("84581482730"); Log.d(getTag(), "Checking the status of the new token: " + strToken); if (getString("token", "").isEmpty()) { Log.d(getTag(), "Not registered, saving the token"); getEditor().putString("token", strToken).commit(); } else { Log.d(getTag(), "Token changed, saving the new token"); getEditor().putString("token", strToken).commit(); } String strName = getString("hostname", "").toUpperCase(); Log.d(getTag(), "Hostname is " + strName); MessageDigest md5Digest = MessageDigest.getInstance("MD5"); byte[] bytHash = md5Digest.digest(strName.getBytes()); StringBuilder sbfHash = new StringBuilder(); for (byte aBytHash : bytHash) { sbfHash.append(Integer.toHexString(aBytHash & 0xFF | 0x100).substring(1, 3)); } String strPath = "http://androprter.appspot.com/set/token" + sbfHash.toString() + "/"; Log.d(getTag(), "Posting token to " + strPath); AsyncHttpClient ascClient = new AsyncHttpClient(); ascClient.setTimeout(5000); ascClient.post(getApplicationContext(), strPath, new StringEntity(strToken, "UTF-8"), "text/plain", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { Log.d(getTag(), "Posted the token successfully"); } @Override public void onFailure(int intCode, Header[] arrHeaders, byte[] arrBytes, Throwable errError) { Log.w(getTag(), "Error posting token due to code " + intCode); } }); } catch (IOException e) { Log.e(getTag(), "Error getting token", e); } catch (Exception e) { Log.e(getTag(), "Unknown error occurred", e); ACRA.getErrorReporter().handleSilentException(e); } } } }
29.725086
112
0.721156
74f48f5c88e07cddf19a0a49887d7f0593008263
4,816
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.hdfs.nfs.nfs3 package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hdfs operator|. name|nfs operator|. name|nfs3 package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Comparator import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Preconditions import|; end_import begin_comment comment|/** * OffsetRange is the range of read/write request. A single point (e.g.,[5,5]) * is not a valid range. */ end_comment begin_class DECL|class|OffsetRange specifier|public class|class name|OffsetRange block|{ DECL|field|ReverseComparatorOnMin specifier|public specifier|static specifier|final name|Comparator argument_list|< name|OffsetRange argument_list|> name|ReverseComparatorOnMin init|= operator|new name|Comparator argument_list|< name|OffsetRange argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|int name|compare parameter_list|( name|OffsetRange name|o1 parameter_list|, name|OffsetRange name|o2 parameter_list|) block|{ if|if condition|( name|o1 operator|. name|getMin argument_list|() operator|== name|o2 operator|. name|getMin argument_list|() condition|) block|{ return|return name|o1 operator|. name|getMax argument_list|() operator|< name|o2 operator|. name|getMax argument_list|() condition|? literal|1 else|: operator|( name|o1 operator|. name|getMax argument_list|() operator|> name|o2 operator|. name|getMax argument_list|() condition|? operator|- literal|1 else|: literal|0 operator|) return|; block|} else|else block|{ return|return name|o1 operator|. name|getMin argument_list|() operator|< name|o2 operator|. name|getMin argument_list|() condition|? literal|1 else|: operator|- literal|1 return|; block|} block|} block|} decl_stmt|; DECL|field|min specifier|private specifier|final name|long name|min decl_stmt|; DECL|field|max specifier|private specifier|final name|long name|max decl_stmt|; DECL|method|OffsetRange (long min, long max) name|OffsetRange parameter_list|( name|long name|min parameter_list|, name|long name|max parameter_list|) block|{ name|Preconditions operator|. name|checkArgument argument_list|( name|min operator|>= literal|0 operator|&& name|max operator|>= literal|0 operator|&& name|min operator|< name|max argument_list|) expr_stmt|; name|this operator|. name|min operator|= name|min expr_stmt|; name|this operator|. name|max operator|= name|max expr_stmt|; block|} DECL|method|getMin () name|long name|getMin parameter_list|() block|{ return|return name|min return|; block|} DECL|method|getMax () name|long name|getMax parameter_list|() block|{ return|return name|max return|; block|} annotation|@ name|Override DECL|method|hashCode () specifier|public name|int name|hashCode parameter_list|() block|{ return|return call|( name|int call|) argument_list|( name|min operator|^ name|max argument_list|) return|; block|} annotation|@ name|Override DECL|method|equals (Object o) specifier|public name|boolean name|equals parameter_list|( name|Object name|o parameter_list|) block|{ if|if condition|( name|o operator|instanceof name|OffsetRange condition|) block|{ name|OffsetRange name|range init|= operator|( name|OffsetRange operator|) name|o decl_stmt|; return|return operator|( name|min operator|== name|range operator|. name|getMin argument_list|() operator|) operator|&& operator|( name|max operator|== name|range operator|. name|getMax argument_list|() operator|) return|; block|} return|return literal|false return|; block|} DECL|method|toString () specifier|public name|String name|toString parameter_list|() block|{ return|return literal|"[" operator|+ name|getMin argument_list|() operator|+ literal|", " operator|+ name|getMax argument_list|() operator|+ literal|")" return|; block|} block|} end_class end_unit
15.192429
814
0.775748