text
stringlengths
7
1.01M
/* * Copyright 2015-2020 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.sagemaker.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A collection of settings used for a job. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/AutoMLJobConfig" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AutoMLJobConfig implements Serializable, Cloneable, StructuredPojo { /** * <p> * How long a job is allowed to run, or how many candidates a job is allowed to generate. * </p> */ private AutoMLJobCompletionCriteria completionCriteria; /** * <p> * Security configuration for traffic encryption or Amazon VPC settings. * </p> */ private AutoMLSecurityConfig securityConfig; /** * <p> * How long a job is allowed to run, or how many candidates a job is allowed to generate. * </p> * * @param completionCriteria * How long a job is allowed to run, or how many candidates a job is allowed to generate. */ public void setCompletionCriteria(AutoMLJobCompletionCriteria completionCriteria) { this.completionCriteria = completionCriteria; } /** * <p> * How long a job is allowed to run, or how many candidates a job is allowed to generate. * </p> * * @return How long a job is allowed to run, or how many candidates a job is allowed to generate. */ public AutoMLJobCompletionCriteria getCompletionCriteria() { return this.completionCriteria; } /** * <p> * How long a job is allowed to run, or how many candidates a job is allowed to generate. * </p> * * @param completionCriteria * How long a job is allowed to run, or how many candidates a job is allowed to generate. * @return Returns a reference to this object so that method calls can be chained together. */ public AutoMLJobConfig withCompletionCriteria(AutoMLJobCompletionCriteria completionCriteria) { setCompletionCriteria(completionCriteria); return this; } /** * <p> * Security configuration for traffic encryption or Amazon VPC settings. * </p> * * @param securityConfig * Security configuration for traffic encryption or Amazon VPC settings. */ public void setSecurityConfig(AutoMLSecurityConfig securityConfig) { this.securityConfig = securityConfig; } /** * <p> * Security configuration for traffic encryption or Amazon VPC settings. * </p> * * @return Security configuration for traffic encryption or Amazon VPC settings. */ public AutoMLSecurityConfig getSecurityConfig() { return this.securityConfig; } /** * <p> * Security configuration for traffic encryption or Amazon VPC settings. * </p> * * @param securityConfig * Security configuration for traffic encryption or Amazon VPC settings. * @return Returns a reference to this object so that method calls can be chained together. */ public AutoMLJobConfig withSecurityConfig(AutoMLSecurityConfig securityConfig) { setSecurityConfig(securityConfig); 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 (getCompletionCriteria() != null) sb.append("CompletionCriteria: ").append(getCompletionCriteria()).append(","); if (getSecurityConfig() != null) sb.append("SecurityConfig: ").append(getSecurityConfig()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AutoMLJobConfig == false) return false; AutoMLJobConfig other = (AutoMLJobConfig) obj; if (other.getCompletionCriteria() == null ^ this.getCompletionCriteria() == null) return false; if (other.getCompletionCriteria() != null && other.getCompletionCriteria().equals(this.getCompletionCriteria()) == false) return false; if (other.getSecurityConfig() == null ^ this.getSecurityConfig() == null) return false; if (other.getSecurityConfig() != null && other.getSecurityConfig().equals(this.getSecurityConfig()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCompletionCriteria() == null) ? 0 : getCompletionCriteria().hashCode()); hashCode = prime * hashCode + ((getSecurityConfig() == null) ? 0 : getSecurityConfig().hashCode()); return hashCode; } @Override public AutoMLJobConfig clone() { try { return (AutoMLJobConfig) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.sagemaker.model.transform.AutoMLJobConfigMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.sql.parser.integrate.asserts.statement.dcl.impl; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.shardingsphere.sql.parser.integrate.asserts.SQLCaseAssertContext; import org.apache.shardingsphere.sql.parser.integrate.asserts.segment.table.TableAssert; import org.apache.shardingsphere.sql.parser.integrate.jaxb.domain.statement.dcl.DenyUserStatementTestCase; import org.apache.shardingsphere.sql.parser.sql.statement.dcl.DenyUserStatement; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * Deny user statement assert. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class DenyUserStatementAssert { /** * Assert deny user statement is correct with expected parser result. * * @param assertContext assert context * @param actual actual deny user statement * @param expected expected deny user statement test case */ public static void assertIs(final SQLCaseAssertContext assertContext, final DenyUserStatement actual, final DenyUserStatementTestCase expected) { assertTable(assertContext, actual, expected); } private static void assertTable(final SQLCaseAssertContext assertContext, final DenyUserStatement actual, final DenyUserStatementTestCase expected) { if (null != expected.getTable()) { assertNotNull(assertContext.getText("Actual table segment should exist."), actual.getTable()); TableAssert.assertIs(assertContext, actual.getTable(), expected.getTable()); } else { assertNull(assertContext.getText("Actual table segment should not exist."), actual.getTable()); } } }
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.cluster; import io.aeron.FragmentAssembler; import io.aeron.Subscription; import io.aeron.cluster.client.ClusterException; import io.aeron.cluster.codecs.*; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; class MemberStatusAdapter implements FragmentHandler, AutoCloseable { private static final int FRAGMENT_POLL_LIMIT = 10; private final MessageHeaderDecoder messageHeaderDecoder = new MessageHeaderDecoder(); private final CanvassPositionDecoder canvassPositionDecoder = new CanvassPositionDecoder(); private final RequestVoteDecoder requestVoteDecoder = new RequestVoteDecoder(); private final VoteDecoder voteDecoder = new VoteDecoder(); private final NewLeadershipTermDecoder newLeadershipTermDecoder = new NewLeadershipTermDecoder(); private final AppendedPositionDecoder appendedPositionDecoder = new AppendedPositionDecoder(); private final CommitPositionDecoder commitPositionDecoder = new CommitPositionDecoder(); private final CatchupPositionDecoder catchupPositionDecoder = new CatchupPositionDecoder(); private final StopCatchupDecoder stopCatchupDecoder = new StopCatchupDecoder(); private final RecoveryPlanQueryDecoder recoveryPlanQueryDecoder = new RecoveryPlanQueryDecoder(); private final RecoveryPlanDecoder recoveryPlanDecoder = new RecoveryPlanDecoder(); private final RecordingLogQueryDecoder recordingLogQueryDecoder = new RecordingLogQueryDecoder(); private final RecordingLogDecoder recordingLogDecoder = new RecordingLogDecoder(); private final AddClusterMemberDecoder addClusterMemberDecoder = new AddClusterMemberDecoder(); private final RemoveClusterMemberDecoder removeClusterMemberDecoder = new RemoveClusterMemberDecoder(); private final ClusterMembersChangeDecoder clusterMembersChangeDecoder = new ClusterMembersChangeDecoder(); private final SnapshotRecordingQueryDecoder snapshotRecordingQueryDecoder = new SnapshotRecordingQueryDecoder(); private final SnapshotRecordingsDecoder snapshotRecordingsDecoder = new SnapshotRecordingsDecoder(); private final JoinClusterDecoder joinClusterDecoder = new JoinClusterDecoder(); private final LeaveClusterDecoder leaveClusterDecoder = new LeaveClusterDecoder(); private final FragmentAssembler fragmentAssembler = new FragmentAssembler(this); private final Subscription subscription; private final MemberStatusListener memberStatusListener; MemberStatusAdapter(final Subscription subscription, final MemberStatusListener memberStatusListener) { this.subscription = subscription; this.memberStatusListener = memberStatusListener; } public void close() { CloseHelper.close(subscription); } public int poll() { return subscription.poll(fragmentAssembler, FRAGMENT_POLL_LIMIT); } @SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { messageHeaderDecoder.wrap(buffer, offset); final int templateId = messageHeaderDecoder.templateId(); switch (templateId) { case CanvassPositionDecoder.TEMPLATE_ID: canvassPositionDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onCanvassPosition( canvassPositionDecoder.logLeadershipTermId(), canvassPositionDecoder.logPosition(), canvassPositionDecoder.followerMemberId()); break; case RequestVoteDecoder.TEMPLATE_ID: requestVoteDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRequestVote( requestVoteDecoder.logLeadershipTermId(), requestVoteDecoder.logPosition(), requestVoteDecoder.candidateTermId(), requestVoteDecoder.candidateMemberId()); break; case VoteDecoder.TEMPLATE_ID: voteDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onVote( voteDecoder.candidateTermId(), voteDecoder.logLeadershipTermId(), voteDecoder.logPosition(), voteDecoder.candidateMemberId(), voteDecoder.followerMemberId(), voteDecoder.vote() == BooleanType.TRUE); break; case NewLeadershipTermDecoder.TEMPLATE_ID: newLeadershipTermDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onNewLeadershipTerm( newLeadershipTermDecoder.logLeadershipTermId(), newLeadershipTermDecoder.logPosition(), newLeadershipTermDecoder.leadershipTermId(), newLeadershipTermDecoder.leaderMemberId(), newLeadershipTermDecoder.logSessionId()); break; case AppendedPositionDecoder.TEMPLATE_ID: appendedPositionDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onAppendedPosition( appendedPositionDecoder.leadershipTermId(), appendedPositionDecoder.logPosition(), appendedPositionDecoder.followerMemberId()); break; case CommitPositionDecoder.TEMPLATE_ID: commitPositionDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onCommitPosition( commitPositionDecoder.leadershipTermId(), commitPositionDecoder.logPosition(), commitPositionDecoder.leaderMemberId()); break; case CatchupPositionDecoder.TEMPLATE_ID: catchupPositionDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onCatchupPosition( catchupPositionDecoder.leadershipTermId(), catchupPositionDecoder.logPosition(), catchupPositionDecoder.followerMemberId()); break; case StopCatchupDecoder.TEMPLATE_ID: stopCatchupDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onStopCatchup( stopCatchupDecoder.replaySessionId(), stopCatchupDecoder.followerMemberId()); break; case RecoveryPlanQueryDecoder.TEMPLATE_ID: recoveryPlanQueryDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRecoveryPlanQuery( recoveryPlanQueryDecoder.correlationId(), recoveryPlanQueryDecoder.requestMemberId(), recoveryPlanQueryDecoder.leaderMemberId()); break; case RecoveryPlanDecoder.TEMPLATE_ID: recoveryPlanDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRecoveryPlan(recoveryPlanDecoder); break; case RecordingLogQueryDecoder.TEMPLATE_ID: recordingLogQueryDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRecordingLogQuery( recordingLogQueryDecoder.correlationId(), recordingLogQueryDecoder.requestMemberId(), recordingLogQueryDecoder.leaderMemberId(), recordingLogQueryDecoder.fromLeadershipTermId(), recordingLogQueryDecoder.count(), recordingLogQueryDecoder.includeSnapshots() == BooleanType.TRUE); break; case RecordingLogDecoder.TEMPLATE_ID: recordingLogDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRecordingLog(recordingLogDecoder); break; case AddClusterMemberDecoder.TEMPLATE_ID: addClusterMemberDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onAddClusterMember( addClusterMemberDecoder.correlationId(), addClusterMemberDecoder.memberEndpoints()); break; case RemoveClusterMemberDecoder.TEMPLATE_ID: removeClusterMemberDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onRemoveClusterMember( removeClusterMemberDecoder.correlationId(), removeClusterMemberDecoder.memberId()); break; case ClusterMembersChangeDecoder.TEMPLATE_ID: clusterMembersChangeDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onClusterMembersChange( clusterMembersChangeDecoder.correlationId(), clusterMembersChangeDecoder.leaderMemberId(), clusterMembersChangeDecoder.activeMembers(), clusterMembersChangeDecoder.passiveMembers()); break; case SnapshotRecordingQueryDecoder.TEMPLATE_ID: snapshotRecordingQueryDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onSnapshotRecordingQuery( snapshotRecordingQueryDecoder.correlationId(), snapshotRecordingQueryDecoder.requestMemberId()); break; case SnapshotRecordingsDecoder.TEMPLATE_ID: snapshotRecordingsDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onSnapshotRecordings( snapshotRecordingsDecoder.correlationId(), snapshotRecordingsDecoder); break; case JoinClusterDecoder.TEMPLATE_ID: joinClusterDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onJoinCluster( joinClusterDecoder.leadershipTermId(), joinClusterDecoder.memberId()); break; case LeaveClusterDecoder.TEMPLATE_ID: leaveClusterDecoder.wrap( buffer, offset + MessageHeaderDecoder.ENCODED_LENGTH, messageHeaderDecoder.blockLength(), messageHeaderDecoder.version()); memberStatusListener.onLeaveCluster( leaveClusterDecoder.leadershipTermId(), leaveClusterDecoder.memberId()); break; default: throw new ClusterException("unknown template id: " + templateId); } } }
package pers.auly.cmcwip; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ // Test classes }) public class CmcwipApplicationTests { // Automatically run all the tests in SuiteClasses }
package ozaydin.serkan.com.image_zoom_view; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("ozaydin.serkan.com.image_zoom_view.test", appContext.getPackageName()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.dao; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import org.apache.skywalking.oap.server.core.CoreModule; import org.apache.skywalking.oap.server.core.config.ConfigService; import org.apache.skywalking.oap.server.core.storage.IHistoryDeleteDAO; import org.apache.skywalking.oap.server.core.storage.model.Model; import org.apache.skywalking.oap.server.core.storage.ttl.StorageTTL; import org.apache.skywalking.oap.server.core.storage.ttl.TTLCalculator; import org.apache.skywalking.oap.server.library.client.jdbc.JDBCClientException; import org.apache.skywalking.oap.server.library.client.jdbc.hikaricp.JDBCHikariCPClient; import org.apache.skywalking.oap.server.library.module.ModuleDefineHolder; import org.apache.skywalking.oap.server.storage.plugin.jdbc.SQLBuilder; import org.joda.time.DateTime; /** * @author wusheng */ public class H2HistoryDeleteDAO implements IHistoryDeleteDAO { private final JDBCHikariCPClient client; private final StorageTTL storageTTL; private final ModuleDefineHolder moduleDefineHolder; public H2HistoryDeleteDAO(ModuleDefineHolder moduleDefineHolder, JDBCHikariCPClient client, StorageTTL storageTTL) { this.client = client; this.storageTTL = storageTTL; this.moduleDefineHolder = moduleDefineHolder; } @Override public void deleteHistory(Model model, String timeBucketColumnName) throws IOException { ConfigService configService = moduleDefineHolder.find(CoreModule.NAME).provider().getService(ConfigService.class); SQLBuilder dataDeleteSQL = new SQLBuilder("delete from " + model.getName() + " where ").append(timeBucketColumnName).append("<= ?"); try (Connection connection = client.getConnection()) { TTLCalculator ttlCalculator; if (model.isRecord()) { ttlCalculator = storageTTL.recordCalculator(); } else { ttlCalculator = storageTTL.metricsCalculator(model.getDownsampling()); } long timeBefore = ttlCalculator.timeBefore(new DateTime(), configService.getDataTTLConfig()); client.execute(connection, dataDeleteSQL.toString(), timeBefore); } catch (JDBCClientException | SQLException e) { throw new IOException(e.getMessage(), e); } } }
package com.gocardless.resources; import com.gocardless.api.Message; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; @Path("/hello") public class InterviewResource { private static final String MESSAGE = "Hello, world!"; @GET @Produces(APPLICATION_JSON) public Message hello() { return new Message(MESSAGE); } }
package com.hyperwallet.android.transfermethod; import com.hyperwallet.android.Hyperwallet; import com.hyperwallet.android.exception.HyperwalletException; import com.hyperwallet.android.exception.HyperwalletRestException; import com.hyperwallet.android.listener.HyperwalletListener; import com.hyperwallet.android.model.Error; import com.hyperwallet.android.model.Errors; import com.hyperwallet.android.model.transfermethod.VenmoAccount; import com.hyperwallet.android.rule.ExternalResourceManager; import com.hyperwallet.android.rule.HyperwalletMockWebServer; import com.hyperwallet.android.rule.HyperwalletSdkMock; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; import java.net.HttpURLConnection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.RecordedRequest; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.CREATED_ON; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.EMAIL; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.STATUS; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.TOKEN; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.TRANSFER_METHOD_COUNTRY; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.TRANSFER_METHOD_CURRENCY; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.TYPE; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodFields.VENMO_ACCOUNT_ID; import static com.hyperwallet.android.model.transfermethod.TransferMethod.TransferMethodTypes.VENMO_ACCOUNT; import static com.hyperwallet.android.util.HttpMethod.PUT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @RunWith(RobolectricTestRunner.class) public class UpdateVenmoAccountTest { private final CountDownLatch mAwait = new CountDownLatch(1); @Rule public HyperwalletMockWebServer mServer = new HyperwalletMockWebServer(); @Rule public HyperwalletSdkMock mHyperwalletSdkMock = new HyperwalletSdkMock(mServer); @Rule public ExternalResourceManager mExternalResourceManager = new ExternalResourceManager(); @Rule public MockitoRule mMockito = MockitoJUnit.rule(); @Mock private HyperwalletListener<VenmoAccount> mListener; @Captor private ArgumentCaptor<VenmoAccount> mVenmoAccountCaptor; @Captor private ArgumentCaptor<HyperwalletException> mExceptionCaptor; @Test public void testUpdateVenmoAccount_withSuccess() throws InterruptedException { String responseBody = mExternalResourceManager.getResourceContent("venmo_account_update_response.json"); mServer.mockResponse().withHttpResponseCode(HttpURLConnection.HTTP_OK).withBody(responseBody).mock(); final VenmoAccount venmoAccount = new VenmoAccount .Builder() .accountId("9876543211") .token("trm-fake-token") .build(); assertThat(venmoAccount.getField(VENMO_ACCOUNT_ID), is("9876543211")); assertThat(venmoAccount.getField(TOKEN), is("trm-fake-token")); Hyperwallet.getDefault().updateVenmoAccount(venmoAccount, mListener); mAwait.await(50, TimeUnit.MILLISECONDS); RecordedRequest recordedRequest = mServer.getRequest(); assertThat(recordedRequest.getMethod(), is(PUT.name())); verify(mListener).onSuccess(mVenmoAccountCaptor.capture()); verify(mListener, never()).onFailure(any(HyperwalletException.class)); VenmoAccount venmoAccountResponse = mVenmoAccountCaptor.getValue(); assertThat(venmoAccountResponse, is(notNullValue())); assertThat(recordedRequest.getPath(), is("/rest/v3/users/test-user-token/venmo-accounts/trm-fake-token")); assertThat(venmoAccountResponse.getField(TOKEN), is("trm-fake-token")); assertThat(venmoAccountResponse.getField(STATUS), is("ACTIVATED")); assertThat(venmoAccountResponse.getField(TYPE), is(VENMO_ACCOUNT)); assertThat(venmoAccountResponse.getField(VENMO_ACCOUNT_ID), is("9876543211")); assertThat(venmoAccountResponse.getField(TRANSFER_METHOD_CURRENCY), is("USD")); assertThat(venmoAccountResponse.getField(TRANSFER_METHOD_COUNTRY), is("US")); assertThat(venmoAccountResponse.getField(CREATED_ON), is("2019-01-09T22:50:14")); } @Test public void testUpdateVenmoAccount_withValidationError() throws InterruptedException { String responseBody = mExternalResourceManager.getResourceContentError( "venmo_account_update_error_response.json"); mServer.mockResponse().withHttpResponseCode(HttpURLConnection.HTTP_BAD_REQUEST).withBody(responseBody).mock(); final VenmoAccount venmoAccount = new VenmoAccount .Builder() .accountId("1234567890") .token("trm-fake-token") .build(); assertThat(venmoAccount.getField(VENMO_ACCOUNT_ID), is("1234567890")); assertThat(venmoAccount.getField(TOKEN), is("trm-fake-token")); Hyperwallet.getDefault().updateVenmoAccount(venmoAccount, mListener); mAwait.await(50, TimeUnit.MILLISECONDS); RecordedRequest recordedRequest = mServer.getRequest(); assertThat(recordedRequest.getMethod(), is(PUT.name())); verify(mListener, never()).onSuccess(any(VenmoAccount.class)); verify(mListener).onFailure(mExceptionCaptor.capture()); HyperwalletException hyperwalletException = mExceptionCaptor.getValue(); assertThat(hyperwalletException, is(notNullValue())); assertThat(((HyperwalletRestException) hyperwalletException).getHttpCode(), is(HttpURLConnection.HTTP_BAD_REQUEST)); assertThat(recordedRequest.getPath(), is("/rest/v3/users/test-user-token/venmo-accounts/trm-fake-token")); Errors errors = hyperwalletException.getErrors(); assertThat(errors, is(notNullValue())); assertThat(errors.getErrors(), hasSize(1)); Error error1 = errors.getErrors().get(0); assertThat(error1.getCode(), is("CONSTRAINT_VIOLATIONS")); assertThat(error1.getMessage(), is("Mobile Number is invalid. The maximum length of this field is 10.")); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import java.util.List; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.spi.RouteStartupOrder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RouteStartupOrderTest extends ContextTestSupport { @Test public void testRouteStartupOrder() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // assert correct order DefaultCamelContext dcc = (DefaultCamelContext)context; List<RouteStartupOrder> order = dcc.getRouteStartupOrder(); assertEquals(4, order.size()); assertEquals("seda://foo", order.get(0).getRoute().getEndpoint().getEndpointUri()); assertEquals("direct://start", order.get(1).getRoute().getEndpoint().getEndpointUri()); assertEquals("seda://bar", order.get(2).getRoute().getEndpoint().getEndpointUri()); assertEquals("direct://bar", order.get(3).getRoute().getEndpoint().getEndpointUri()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").startupOrder(2).to("seda:foo"); from("seda:foo").startupOrder(1).to("mock:result"); from("direct:bar").startupOrder(9).to("seda:bar"); from("seda:bar").startupOrder(5).to("mock:other"); } }; } }
/* * Copyright (C) 2004-2008 Jive Software. 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.jivesoftware.openfire.spi; import org.jivesoftware.openfire.XMPPServerInfo; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; /** * Implements the server info for a basic server. Optimization opportunities * in reusing this object the data is relatively static. * * @author Iain Shigeoka */ public class XMPPServerInfoImpl implements XMPPServerInfo { private static final Logger Log = LoggerFactory.getLogger( XMPPServerInfoImpl.class ); private final Date startDate; public static final Version VERSION = new Version(4, 3, 0, Version.ReleaseStatus.Alpha, -1 ); /** * Simple constructor * * @param startDate the server's last start time (can be null indicating * it hasn't been started). */ public XMPPServerInfoImpl(Date startDate) { this.startDate = startDate; } @Override public Version getVersion() { return VERSION; } @Override public String getHostname() { final String fqdn = JiveGlobals.getProperty( "xmpp.fqdn" ); if ( fqdn != null && !fqdn.trim().isEmpty() ) { return fqdn.trim().toLowerCase(); } try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(); } catch (UnknownHostException ex) { Log.warn( "Unable to determine local hostname.", ex ); return "localhost"; } } @Override public void setHostname( String fqdn ) { if ( fqdn == null || fqdn.isEmpty() ) { JiveGlobals.deleteProperty( "xmpp.fqdn" ); } else { JiveGlobals.setProperty( "xmpp.fqdn", fqdn.toLowerCase() ); } } @Override public String getXMPPDomain() { return JiveGlobals.getProperty("xmpp.domain", getHostname() ).toLowerCase(); } @Override public Date getLastStarted() { return startDate; } }
package com.patrick.maaltijdapp.model.data; /** * Created by Patrick on 16/01/2018. */ /** * Provides specific data operations */ public class DAOFactory { private static final String TAG = DAOFactory.class.getSimpleName(); private SQLiteLocalDatabase db; /** * Initializes a new instance of the DAOFactory class from the specified instance of the SQLiteLocalDatabase class. * * @param db The SQLite database to use. */ public DAOFactory(SQLiteLocalDatabase db) { this.db = db; } /** * @return Returns a new StudentDAO */ public StudentDAO getStudentDAO() { return new StudentDAO(db); } /** * @return Returns a new MealDAO */ public MealDAO getMealDAO() { return new MealDAO(db, getStudentDAO()); } /** * @return Returns a new FellowEaterDAO */ public FellowEaterDAO getFellowEaterDAO() { return new FellowEaterDAO(db, getStudentDAO(), getMealDAO()); } }
/** * The MIT License (MIT) * * Copyright (c) 2021 nobark (tools4j), Marco Terzer, Anton Anufriev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.tools4j.nobark.run; import org.tools4j.nobark.loop.Step; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * Shutdownable is a running service such as a thread that can be shutdown orderly or abruptly in a way similar to * {@link ExecutorService}. */ public interface Shutdownable { /** * Initiates an orderly shutdown in which the service will be continue to perform its duties * as long as there is work to be done. For instance for a sequence of steps, the service could * continue to invoke the steps' {@link Step#perform() perform()} methods until all invocations * yield false (indicating that no work was done). * <p> * This method does not wait for for termination; use {@link #awaitTermination awaitTermination} * to do that. * <p> * Invocation has no additional effect if already shut down. */ void shutdown(); /** * Initiates an immediate shutdown in which the service will stop even if there is more work * to be done. For instance for a sequence of steps, the service could abort invocation of the * steps' {@link Step#perform() perform()} irrespective of prior invocation results. * <p> * This method does not wait for for termination; use {@link #awaitTermination awaitTermination} * to do that. * <p> * Invocation has no additional effect if already shut down. * * @return list of tasks that never commenced execution if any, otherwise an empty list */ List<Runnable> shutdownNow(); /** * Returns {@code true} if this service has been shut down. * * @return {@code true} if this service has been shut down */ boolean isShutdown(); /** * Returns {@code true} if this service has terminated. * * @return {@code true} if the service has terminated. */ boolean isTerminated(); /** * Blocks until this service has terminated, or the timeout occurs, whichever happens first. * Zero timeout means waiting forever. * * @param timeout the maximum time to wait, zero to wait indefinitely * @param unit the time unit of the timeout argument * @return {@code true} if this executor terminated and * {@code false} if the timeout elapsed before termination * @throws IllegalStateException if any thread has interrupted the current thread */ boolean awaitTermination(long timeout, TimeUnit unit); }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.grid.node.config; import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverInfo; import org.openqa.selenium.chrome.ChromeDriverInfo; import org.openqa.selenium.events.EventBus; import org.openqa.selenium.events.local.GuavaEventBus; import org.openqa.selenium.grid.config.Config; import org.openqa.selenium.grid.config.MapConfig; import org.openqa.selenium.grid.config.TomlConfig; import org.openqa.selenium.grid.data.CreateSessionRequest; import org.openqa.selenium.grid.node.ActiveSession; import org.openqa.selenium.grid.node.SessionFactory; import org.openqa.selenium.grid.node.local.LocalNode; import org.openqa.selenium.grid.security.Secret; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.http.HttpClient; import org.openqa.selenium.remote.tracing.DefaultTestTracer; import org.openqa.selenium.remote.tracing.Tracer; import java.io.StringReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.spy; public class NodeOptionsTest { private Tracer tracer; private HttpClient.Factory clientFactory; private LocalNode.Builder builder; private LocalNode.Builder builderSpy; @Before public void setUp() throws URISyntaxException { tracer = DefaultTestTracer.createTracer(); EventBus bus = new GuavaEventBus(); clientFactory = HttpClient.Factory.createDefault(); URI uri = new URI("http://localhost:1234"); builder = LocalNode.builder(tracer, bus, uri, uri, new Secret("wensleydale")); builderSpy = spy(builder); } @Test public void canConfigureNodeWithDriverDetection() { assumeFalse("We don't have driver servers in PATH when we run unit tests", Boolean.parseBoolean(System.getenv("TRAVIS"))); assumeTrue("ChromeDriver needs to be available", new ChromeDriverInfo().isAvailable()); Config config = new MapConfig(singletonMap( "node", singletonMap("detect-drivers", "true"))); List<WebDriverInfo> reported = new ArrayList<>(); new NodeOptions(config).getSessionFactories(info -> { reported.add(info); return Collections.emptySet(); }); String expected = new ChromeDriverInfo().getDisplayName(); reported.stream() .filter(info -> expected.equals(info.getDisplayName())) .findFirst() .orElseThrow(() -> new AssertionError("Unable to find Chrome info")); } @Test public void shouldDetectCorrectDriversOnWindows() { assumeTrue(Platform.getCurrent().is(Platform.WINDOWS)); assumeFalse("We don't have driver servers in PATH when we run unit tests", Boolean.getBoolean("TRAVIS")); Config config = new MapConfig(singletonMap( "node", singletonMap("detect-drivers", "true"))); List<WebDriverInfo> reported = new ArrayList<>(); new NodeOptions(config).getSessionFactories(info -> { reported.add(info); return Collections.emptySet(); }); assertThat(reported).is(supporting("chrome")); assertThat(reported).is(supporting("firefox")); assertThat(reported).is(supporting("internet explorer")); assertThat(reported).is(supporting("MicrosoftEdge")); assertThat(reported).isNot(supporting("safari")); } @Test public void shouldDetectCorrectDriversOnMac() { assumeTrue(Platform.getCurrent().is(Platform.MAC)); assumeFalse("We don't have driver servers in PATH when we run unit tests", Boolean.getBoolean("TRAVIS")); Config config = new MapConfig(singletonMap( "node", singletonMap("detect-drivers", "true"))); List<WebDriverInfo> reported = new ArrayList<>(); new NodeOptions(config).getSessionFactories(info -> { reported.add(info); return Collections.emptySet(); }); LocalNode node = builder.build(); assertThat(reported).is(supporting("chrome")); assertThat(reported).is(supporting("firefox")); assertThat(reported).isNot(supporting("internet explorer")); assertThat(reported).is(supporting("MicrosoftEdge")); assertThat(reported).is(supporting("safari")); } @Test public void canConfigureNodeWithoutDriverDetection() { Config config = new MapConfig(singletonMap( "node", singletonMap("detect-drivers", "false"))); List<WebDriverInfo> reported = new ArrayList<>(); new NodeOptions(config).getSessionFactories(info -> { reported.add(info); return Collections.emptySet(); }); assertThat(reported).isEmpty(); } @Test public void detectDriversByDefault() { Config config = new MapConfig(emptyMap()); List<WebDriverInfo> reported = new ArrayList<>(); new NodeOptions(config).getSessionFactories(info -> { reported.add(info); return Collections.emptySet(); }); assertThat(reported).isNotEmpty(); } @Test public void canBeConfiguredToUseHelperClassesToCreateSessionFactories() { Capabilities caps = new ImmutableCapabilities("browserName", "cheese"); StringBuilder capsString = new StringBuilder(); new Json().newOutput(capsString).setPrettyPrint(false).write(caps); Config config = new TomlConfig(new StringReader(String.format( "[node]\n" + "detect-drivers = false\n" + "driver-factories = [" + " \"%s\",\n" + " \"%s\"\n" + "]", HelperFactory.class.getName(), capsString.toString().replace("\"", "\\\"")))); NodeOptions options = new NodeOptions(config); Map<Capabilities, Collection<SessionFactory>> factories = options.getSessionFactories(info -> emptySet()); Collection<SessionFactory> sessionFactories = factories.get(caps); assertThat(sessionFactories).size().isEqualTo(1); assertThat(sessionFactories.iterator().next()).isInstanceOf(SessionFactory.class); } private Condition<? super List<? extends WebDriverInfo>> supporting(String name) { return new Condition<>( infos -> infos.stream().anyMatch(info -> name.equals(info.getCanonicalCapabilities().getBrowserName())), "supporting %s", name); } public static class HelperFactory { public static SessionFactory create(Config config, Capabilities caps) { return new SessionFactory() { @Override public Optional<ActiveSession> apply(CreateSessionRequest createSessionRequest) { return Optional.empty(); } @Override public boolean test(Capabilities capabilities) { return true; } }; } } }
package base; import javassist.*; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; import java.lang.reflect.Method; public class MethodUtil { public static String[] getAllParamaterName(Method method) throws NotFoundException { Class<?> clazz = method.getDeclaringClass(); ClassPool pool = ClassPool.getDefault(); CtClass clz = pool.get(clazz.getName()); CtClass[] params = new CtClass[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { params[i] = pool.getCtClass(method.getParameterTypes()[i].getName()); } CtMethod cm = clz.getDeclaredMethod(method.getName(), params); MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; String[] paramNames = new String[cm.getParameterTypes().length]; for (int i = 0; i < paramNames.length; i++) { paramNames[i] = attr.variableName(i + pos); } return paramNames; } public static String[] getAllParamaterName(CtMethod cm) throws NotFoundException { MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; String[] paramNames = new String[cm.getParameterTypes().length]; for (int i = 0; i < paramNames.length; i++) { paramNames[i] = attr.variableName(i + pos); } return paramNames; } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seanlab.dalin.mlkit.md.java.productsearch; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import androidx.annotation.NonNull; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Tasks; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.common.FirebaseVisionImage; //import com.google.firebase.ml.vision.label.FirebaseVisionCloudImageLabelerOptions; //import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel; //import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler; import com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions; import com.google.firebase.ml.vision.text.FirebaseVisionText; import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer; import com.seanlab.dalin.mlkit.md.java.objectdetection.DetectedObject; import com.google.firebase.ml.vision.text.RecognizedLanguage; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //import com.google.firebase.ml.md.java.objectdetection.DetectedObject; /** A fake search engine to help simulate the complete work flow. */ public class SearchEngineCloudText { private static final String TAG = "SearchEngineCloudland"; private Bitmap searchbitmap; private final FirebaseVisionTextRecognizer detector; public interface SearchResultListener { void onSearchCompleted(DetectedObject object, List<Product> productList); } private final RequestQueue searchRequestQueue; private final ExecutorService requestCreationExecutor; public SearchEngineCloudText(Context context) { searchRequestQueue = Volley.newRequestQueue(context); requestCreationExecutor = Executors.newSingleThreadExecutor(); //initial FirebaseVisionCloudTextRecognizerOptions options = new FirebaseVisionCloudTextRecognizerOptions.Builder() .setLanguageHints(Arrays.asList("en", "hi")) .build(); detector = FirebaseVision.getInstance().getCloudTextRecognizer(options); } public void search(DetectedObject object, SearchResultListener listener) { // Crops the object image out of the full image is expensive, so do it off the UI thread. Tasks.call(requestCreationExecutor, () -> createRequest(object)) //------------------------------------------------------------- .addOnSuccessListener(new OnSuccessListener<JsonObjectRequest>() { @Override public void onSuccess(JsonObjectRequest jsonObjectRequest) { //sean searchbitmap = object.getBitmap(); FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(searchbitmap); detector.processImage(image) .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() { @Override public void onSuccess(FirebaseVisionText firebaseVisionText) { Log.d(TAG, "block.size: " + firebaseVisionText.getTextBlocks().size()); List<Product> productList = new ArrayList<>(); for(FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()){ Log.d(TAG, "block.text: " + block.getText()); String blockText = block.getText(); Float blockConfidence = block.getConfidence(); Log.d(TAG, "blockConfidence: " + blockConfidence); List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages(); Point[] blockCornerPoints = block.getCornerPoints(); Rect blockFrame = block.getBoundingBox(); for (FirebaseVisionText.Line line: block.getLines()) { String lineText = line.getText(); Log.d(TAG, "lineText: " + lineText); Float lineConfidence = line.getConfidence(); Log.d(TAG, "lineConfidence: " + lineConfidence); List<RecognizedLanguage> lineLanguages = line.getRecognizedLanguages(); Point[] lineCornerPoints = line.getCornerPoints(); Rect lineFrame = line.getBoundingBox(); for (FirebaseVisionText.Element element: line.getElements()) { String elementText = element.getText(); Float elementConfidence = element.getConfidence(); Log.d(TAG, "elementText: " + elementText); Log.d(TAG, "elementConfidence: " + elementConfidence); productList.add( new Product("", elementText , elementConfidence.toString() +" %" )); List<RecognizedLanguage> elementLanguages = element.getRecognizedLanguages(); Point[] elementCornerPoints = element.getCornerPoints(); Rect elementFrame = element.getBoundingBox(); } } } // } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { List<Product> productList = new ArrayList<>(); for (int i = 0; i < 5; i++) { productList.add( new Product( "", "MLkit Fail " + i, "Product subtitle " + i)); } listener.onSearchCompleted(object, productList); } }) ; } }) .addOnFailureListener( e -> { Log.e(TAG, "Failed to create product search request!", e); // Remove the below dummy code after your own product search backed hooked up. List<Product> productList = new ArrayList<>(); for (int i = 0; i < 3; i++) { productList.add( new Product( "", "Search Fail " + i, "Product subtitle " + i)); } listener.onSearchCompleted(object, productList); }); } private JsonObjectRequest createRequest(DetectedObject searchingObject) { byte[] objectImageData = searchingObject.getImageData(); if (objectImageData == null) { //throw new Exception("Failed to get object image data!"); } // Hooks up with your own product search backend here. Log.e(TAG, "SEAN:image lenght" +objectImageData.length); //inputBitmap=searchingObject.getBitmap(); List<Product> productList = new ArrayList<>(); for (int i = 0; i < 10; i++) { productList.add( new Product( "", "Product title " + i, "Product subtitle " + i)); } return null; //throw new Exception("Hooks up with your own product search backend."); } public void shutdown() { searchRequestQueue.cancelAll(TAG); requestCreationExecutor.shutdown(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.db.compaction; import java.util.Collection; import java.util.concurrent.ExecutionException; import com.google.common.collect.Iterables; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.cql3.statements.schema.CreateTableStatement; import org.apache.cassandra.db.*; import org.apache.cassandra.db.partitions.ImmutableBTreePartition; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.schema.CachingParams; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import static org.junit.Assert.*; import static org.apache.cassandra.Util.dk; public class CompactionsPurgeTest { private static final String KEYSPACE1 = "CompactionsPurgeTest1"; private static final String CF_STANDARD1 = "Standard1"; private static final String CF_STANDARD2 = "Standard2"; private static final String KEYSPACE2 = "CompactionsPurgeTest2"; private static final String KEYSPACE_CACHED = "CompactionsPurgeTestCached"; private static final String CF_CACHED = "CachedCF"; private static final String KEYSPACE_CQL = "cql_keyspace"; private static final String CF_CQL = "table1"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD2)); SchemaLoader.createKeyspace(KEYSPACE2, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE2, CF_STANDARD1)); SchemaLoader.createKeyspace(KEYSPACE_CACHED, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE_CACHED, CF_CACHED).caching(CachingParams.CACHE_EVERYTHING)); SchemaLoader.createKeyspace(KEYSPACE_CQL, KeyspaceParams.simple(1), CreateTableStatement.parse("CREATE TABLE " + CF_CQL + " (" + "k int PRIMARY KEY," + "v1 text," + "v2 int" + ")", KEYSPACE_CQL)); } @Test public void testMajorCompactionPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // deletes for (int i = 0; i < 10; i++) { RowUpdateBuilder.deleteRow(cfs.metadata(), 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // resurrect one column RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 2, key); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // major compact and test that all columns but the resurrected one is completely gone FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, Integer.MAX_VALUE, false)); cfs.invalidateCachedPartition(dk(key)); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(1, partition.rowCount()); } @Test public void testMajorCompactionPurgeTombstonesWithMaxTimestamp() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // deletes for (int i = 0; i < 10; i++) { RowUpdateBuilder.deleteRow(cfs.metadata(), Long.MAX_VALUE, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // major compact - tombstones should be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, Integer.MAX_VALUE, false)); // resurrect one column RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 2, key); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); cfs.invalidateCachedPartition(dk(key)); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(1, partition.rowCount()); } @Test public void testMajorCompactionPurgeTopLevelTombstoneWithMaxTimestamp() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); new Mutation.PartitionUpdateCollector(KEYSPACE1, dk(key)) .add(PartitionUpdate.fullPartitionDelete(cfs.metadata(), dk(key), Long.MAX_VALUE, FBUtilities.nowInSeconds())) .build() .applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // major compact - tombstones should be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, Integer.MAX_VALUE, false)); // resurrect one column RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 2, key); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); cfs.invalidateCachedPartition(dk(key)); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(1, partition.rowCount()); } @Test public void testMajorCompactionPurgeRangeTombstoneWithMaxTimestamp() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); new RowUpdateBuilder(cfs.metadata(), Long.MAX_VALUE, dk(key)) .addRangeTombstone(String.valueOf(0), String.valueOf(9)).build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // major compact - tombstones should be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, Integer.MAX_VALUE, false)); // resurrect one column RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 2, key); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); cfs.invalidateCachedPartition(dk(key)); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(1, partition.rowCount()); } @Test public void testMinorCompactionPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE2); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); for (int k = 1; k <= 2; ++k) { String key = "key" + k; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // deletes for (int i = 0; i < 10; i++) { RowUpdateBuilder.deleteRow(cfs.metadata(), 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); } DecoratedKey key1 = Util.dk("key1"); DecoratedKey key2 = Util.dk("key2"); // flush, remember the current sstable and then resurrect one column // for first key. Then submit minor compaction on remembered sstables. cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); Collection<SSTableReader> sstablesIncomplete = cfs.getLiveSSTables(); RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 2, "key1"); builder.clustering(String.valueOf(5)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); try (CompactionTasks tasks = cfs.getCompactionStrategyContainer().getUserDefinedTasks(sstablesIncomplete, Integer.MAX_VALUE)) { Iterables.getOnlyElement(tasks).execute(); } // verify that minor compaction does GC when key is provably not // present in a non-compacted sstable Util.assertEmpty(Util.cmd(cfs, key2).build()); // verify that minor compaction still GC when key is present // in a non-compacted sstable but the timestamp ensures we won't miss anything ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key1).build()); assertEquals(1, partition.rowCount()); } /** * verify that we don't drop tombstones during a minor compaction that might still be relevant */ @Test public void testMinTimestampPurge() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE2); String cfName = "Standard1"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); final boolean enforceStrictLiveness = cfs.metadata().enforceStrictLiveness(); String key3 = "key3"; // inserts new RowUpdateBuilder(cfs.metadata(), 8, key3) .clustering("c1") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); new RowUpdateBuilder(cfs.metadata(), 8, key3) .clustering("c2") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // delete c1 RowUpdateBuilder.deleteRow(cfs.metadata(), 10, key3, "c1").applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); Collection<SSTableReader> sstablesIncomplete = cfs.getLiveSSTables(); // delete c2 so we have new delete in a diffrent SSTable RowUpdateBuilder.deleteRow(cfs.metadata(), 9, key3, "c2").applyUnsafe(); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // compact the sstables with the c1/c2 data and the c1 tombstone try (CompactionTasks tasks = cfs.getCompactionStrategyContainer().getUserDefinedTasks(sstablesIncomplete, Integer.MAX_VALUE)) { Iterables.getOnlyElement(tasks).execute(); } // We should have both the c1 and c2 tombstones still. Since the min timestamp in the c2 tombstone // sstable is older than the c1 tombstone, it is invalid to throw out the c1 tombstone. ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key3).build()); assertEquals(2, partition.rowCount()); for (Row row : partition) assertFalse(row.hasLiveData(FBUtilities.nowInSeconds(), enforceStrictLiveness)); } @Test public void testCompactionPurgeOneFile() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE1); String cfName = "Standard2"; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key1"; // inserts for (int i = 0; i < 5; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes for (int i = 0; i < 5; i++) { RowUpdateBuilder.deleteRow(cfs.metadata(), 1, key, String.valueOf(i)).applyUnsafe(); } cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); assertEquals(String.valueOf(cfs.getLiveSSTables()), 1, cfs.getLiveSSTables().size()); // inserts & deletes were in the same memtable -> only deletes in sstable // compact and test that the row is completely gone Util.compactAll(cfs, Integer.MAX_VALUE).get(); assertTrue(cfs.getLiveSSTables().isEmpty()); Util.assertEmpty(Util.cmd(cfs, key).build()); } @Test public void testCompactionPurgeCachedRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); String keyspaceName = KEYSPACE_CACHED; String cfName = CF_CACHED; Keyspace keyspace = Keyspace.open(keyspaceName); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key3"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), 0, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes partition Mutation.PartitionUpdateCollector rm = new Mutation.PartitionUpdateCollector(KEYSPACE_CACHED, dk(key)); rm.add(PartitionUpdate.fullPartitionDelete(cfs.metadata(), dk(key), 1, FBUtilities.nowInSeconds())); rm.build().applyUnsafe(); // Adds another unrelated partition so that the sstable is not considered fully expired. We do not // invalidate the row cache in that latter case. new RowUpdateBuilder(cfs.metadata(), 0, "key4").clustering("c").add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER).build().applyUnsafe(); // move the key up in row cache (it should not be empty since we have the partition deletion info) assertFalse(Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()).isEmpty()); // flush and major compact cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); Util.compactAll(cfs, Integer.MAX_VALUE).get(); // Since we've force purging (by passing MAX_VALUE for gc_before), the row should have been invalidated and we should have no deletion info anymore Util.assertEmpty(Util.cmd(cfs, key).build()); } @Test public void testCompactionPurgeTombstonedRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); String keyspaceName = KEYSPACE1; String cfName = "Standard1"; Keyspace keyspace = Keyspace.open(keyspaceName); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); String key = "key3"; // inserts for (int i = 0; i < 10; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), i, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // deletes partition with timestamp such that not all columns are deleted Mutation.PartitionUpdateCollector rm = new Mutation.PartitionUpdateCollector(KEYSPACE1, dk(key)); rm.add(PartitionUpdate.fullPartitionDelete(cfs.metadata(), dk(key), 4, FBUtilities.nowInSeconds())); rm.build().applyUnsafe(); ImmutableBTreePartition partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertFalse(partition.partitionLevelDeletion().isLive()); // flush and major compact (with tombstone purging) cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); Util.compactAll(cfs, Integer.MAX_VALUE).get(); assertFalse(Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()).isEmpty()); // re-inserts with timestamp lower than delete for (int i = 0; i < 5; i++) { RowUpdateBuilder builder = new RowUpdateBuilder(cfs.metadata(), i, key); builder.clustering(String.valueOf(i)) .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build().applyUnsafe(); } // Check that the second insert went in partition = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, key).build()); assertEquals(10, partition.rowCount()); } @Test public void testRowTombstoneObservedBeforePurging() { String keyspace = "cql_keyspace"; String table = "table1"; ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(table); cfs.disableAutoCompaction(); // write a row out to one sstable QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v1, v2) VALUES (%d, '%s', %d)", keyspace, table, 1, "foo", 1)); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); UntypedResultSet result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(1, result.size()); // write a row tombstone out to a second sstable QueryProcessor.executeInternal(String.format("DELETE FROM %s.%s WHERE k = %d", keyspace, table, 1)); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // basic check that the row is considered deleted assertEquals(2, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); // compact the two sstables with a gcBefore that does *not* allow the row tombstone to be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, (int) (System.currentTimeMillis() / 1000) - 10000, false)); // the data should be gone, but the tombstone should still exist assertEquals(1, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); // write a row out to one sstable QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v1, v2) VALUES (%d, '%s', %d)", keyspace, table, 1, "foo", 1)); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); assertEquals(2, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(1, result.size()); // write a row tombstone out to a different sstable QueryProcessor.executeInternal(String.format("DELETE FROM %s.%s WHERE k = %d", keyspace, table, 1)); cfs.forceBlockingFlush(ColumnFamilyStore.FlushReason.UNIT_TESTS); // compact the two sstables with a gcBefore that *does* allow the row tombstone to be purged FBUtilities.waitOnFutures(CompactionManager.instance.submitMaximal(cfs, (int) (System.currentTimeMillis() / 1000) + 10000, false)); // both the data and the tombstone should be gone this time assertEquals(0, cfs.getLiveSSTables().size()); result = QueryProcessor.executeInternal(String.format("SELECT * FROM %s.%s WHERE k = %d", keyspace, table, 1)); assertEquals(0, result.size()); } }
/* * ============================================================================ * GNU Lesser General Public License * ============================================================================ * * BYDAN - Free Java BYDAN library. * Copyright (C) 2008 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. * * BYDAN Corporation */ package com.bydan.erp.facturacion.util; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.io.Serializable; import java.util.Date; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityConstantesFunciones; @SuppressWarnings("unused") public class ParametroFactuConstantesFuncionesAdditional extends GeneralEntityConstantesFunciones { public ParametroFactuConstantesFuncionesAdditional () { } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * 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.zaproxy.zap.extension.websocket.brk; import org.apache.log4j.Logger; import org.zaproxy.zap.extension.brk.BreakpointMessageHandler2; import org.zaproxy.zap.extension.websocket.ExtensionWebSocket; import org.zaproxy.zap.extension.websocket.WebSocketException; import org.zaproxy.zap.extension.websocket.WebSocketFuzzMessageDTO; import org.zaproxy.zap.extension.websocket.WebSocketMessage; import org.zaproxy.zap.extension.websocket.WebSocketMessage.Direction; import org.zaproxy.zap.extension.websocket.WebSocketMessageDTO; import org.zaproxy.zap.extension.websocket.WebSocketObserver; import org.zaproxy.zap.extension.websocket.WebSocketProxy; import org.zaproxy.zap.extension.websocket.WebSocketProxy.Mode; import org.zaproxy.zap.extension.websocket.WebSocketProxy.State; import org.zaproxy.zap.extension.websocket.db.WebSocketStorage; /** * Gets notified about WebSocket messages and checks if breakpoint applies. */ public class WebSocketProxyListenerBreak implements WebSocketObserver { private static final Logger logger = Logger.getLogger(WebSocketProxyListenerBreak.class); private BreakpointMessageHandler2 wsBrkMessageHandler; private ExtensionWebSocket extension; public static final int WEBSOCKET_OBSERVING_ORDER = WebSocketStorage.WEBSOCKET_OBSERVING_ORDER - 5; public WebSocketProxyListenerBreak(ExtensionWebSocket extension, BreakpointMessageHandler2 messageHandler) { this.extension = extension; this.wsBrkMessageHandler = messageHandler; } @Override public int getObservingOrder() { // should be the last one to be notified before saving/showing the // message return WEBSOCKET_OBSERVING_ORDER; } @Override public boolean onMessageFrame(int channelId, WebSocketMessage wsMessage) { boolean continueNotifying = false; WebSocketMessageDTO message = wsMessage.getDTO(); if (!extension.isSafe(message)) { // not safe => do not catch return true; } // message is safe => no need to set onlyIfInScope parameter to true if (Mode.SERVER.equals(wsMessage.getProxyMode())) { // These are typically API calls, breaking on these would make the API unusable return true; } if (message instanceof WebSocketFuzzMessageDTO) { // as this message was sent by some fuzzer, do not catch it continueNotifying = true; return continueNotifying; } if (!wsMessage.isFinished()) { boolean isRequest = (wsMessage.getDirection().equals(Direction.OUTGOING)); // already safe => onlyIfInScope can be false if (wsBrkMessageHandler.isBreakpoint(message, isRequest, false)) { // prevent forwarding unfinished message when there is a breakpoint // wait until all frames are received, before processing // (showing/saving/etc.) continueNotifying = false; } else { // gain performance by allowing each frame to be forwarded // immediately, as this frame is not changed continueNotifying = true; } return continueNotifying; } if (message.isOutgoing) { // already safe => onlyIfInScope can be false if (wsBrkMessageHandler.handleMessageReceivedFromClient(message, false)) { // As the DTO that is shown and modified in the // Request/Response panels we must set the content to message // here. setPayload(wsMessage, message.payload); continueNotifying = true; } } else { // already safe => onlyIfInScope can be false if (wsBrkMessageHandler.handleMessageReceivedFromServer(message, false)) { setPayload(wsMessage, message.payload); continueNotifying = true; } } return continueNotifying; } @Override public void onStateChange(State state, WebSocketProxy proxy) { // no need to do something on state change } private void setPayload(WebSocketMessage message, Object payload) { try { if (payload instanceof String) { message.setReadablePayload((String) payload); } else if (payload instanceof byte[]) { message.setPayload((byte[]) payload); } } catch (WebSocketException e) { logger.error(e); } } }
package io.github.joaoh1.okzoomer.client.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import io.github.joaoh1.okzoomer.client.utils.ZoomUtils; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; //TODO - Move this to Fabric API once the bikeshed is done. @Mixin(MinecraftClient.class) public class MinecraftClientMixin { @Inject(at = @At("TAIL"), method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;)V") public void resetZoomLimitations(Screen screen, CallbackInfo info) { ZoomUtils.disableZoom = false; ZoomUtils.disableZoomScrolling = false; ZoomUtils.forceClassicPreset = false; } }
package com.github.utransnet.utranscalc.server.data.services; import com.github.utransnet.utranscalc.server.data.*; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by Artem on 04.06.2018. */ public interface BaseObjectMaterialRepository extends JpaRepository<BaseObjectMaterial, Long> { List<BaseObjectMaterial> findAllByBaseObject(BaseObject baseObject); List<BaseObjectMaterial> findAllByMaterial(Material material); }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.client; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Destination; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.ProxyConnectionFactory; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V1; import static org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V2; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; public class HttpClientProxyProtocolTest { private Server server; private ServerConnector connector; private HttpClient client; private void startServer(Handler handler) throws Exception { QueuedThreadPool serverThreads = new QueuedThreadPool(); serverThreads.setName("server"); server = new Server(serverThreads); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); connector = new ServerConnector(server, 1, 1, proxy, http); server.addConnector(connector); server.setHandler(handler); server.start(); } private void startClient() throws Exception { QueuedThreadPool clientThreads = new QueuedThreadPool(); clientThreads.setName("client"); client = new HttpClient(); client.setExecutor(clientThreads); client.setRemoveIdleDestinations(false); client.start(); } @AfterEach public void dispose() throws Exception { if (server != null) server.stop(); if (client != null) client.stop(); } @Test public void testClientProxyProtocolV1() throws Exception { startServer(new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString()); response.getOutputStream().print(request.getRemotePort()); } }); startClient(); int serverPort = connector.getLocalPort(); int clientPort = ThreadLocalRandom.current().nextInt(1024, 65536); V1.Tag tag = new V1.Tag("127.0.0.1", clientPort); ContentResponse response = client.newRequest("localhost", serverPort) .tag(tag) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); } @Test public void testClientProxyProtocolV1Unknown() throws Exception { startServer(new EmptyServerHandler()); startClient(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .tag(V1.Tag.UNKNOWN) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test public void testClientProxyProtocolV2() throws Exception { startServer(new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString()); response.getOutputStream().print(request.getRemotePort()); } }); startClient(); int serverPort = connector.getLocalPort(); int clientPort = ThreadLocalRandom.current().nextInt(1024, 65536); V2.Tag tag = new V2.Tag("127.0.0.1", clientPort); ContentResponse response = client.newRequest("localhost", serverPort) .tag(tag) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); } @Test public void testClientProxyProtocolV2Local() throws Exception { startServer(new EmptyServerHandler()); startClient(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .tag(V2.Tag.LOCAL) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test public void testClientProxyProtocolV2WithVectors() throws Exception { String tlsVersion = "TLSv1.3"; byte[] tlsVersionBytes = tlsVersion.getBytes(StandardCharsets.US_ASCII); startServer(new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { EndPoint endPoint = jettyRequest.getHttpChannel().getEndPoint(); assertTrue(endPoint instanceof ProxyConnectionFactory.ProxyEndPoint); ProxyConnectionFactory.ProxyEndPoint proxyEndPoint = (ProxyConnectionFactory.ProxyEndPoint)endPoint; if (target.equals("/tls_version")) assertEquals(tlsVersion, proxyEndPoint.getAttribute(ProxyConnectionFactory.TLS_VERSION)); response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString()); response.getOutputStream().print(request.getRemotePort()); } }); startClient(); int serverPort = connector.getLocalPort(); int clientPort = ThreadLocalRandom.current().nextInt(1024, 65536); int typeTLS = 0x20; byte[] dataTLS = new byte[1 + 4 + (1 + 2 + tlsVersionBytes.length)]; dataTLS[0] = 0x01; // CLIENT_SSL dataTLS[5] = 0x21; // SUBTYPE_SSL_VERSION dataTLS[6] = 0x00; // Length, hi byte dataTLS[7] = (byte)tlsVersionBytes.length; // Length, lo byte System.arraycopy(tlsVersionBytes, 0, dataTLS, 8, tlsVersionBytes.length); V2.Tag.TLV tlv = new V2.Tag.TLV(typeTLS, dataTLS); V2.Tag tag = new V2.Tag("127.0.0.1", clientPort, Collections.singletonList(tlv)); ContentResponse response = client.newRequest("localhost", serverPort) .path("/tls_version") .tag(tag) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); // Make another request with the same address information, but different TLV. V2.Tag.TLV tlv2 = new V2.Tag.TLV(0x01, "http/1.1".getBytes(StandardCharsets.UTF_8)); V2.Tag tag2 = new V2.Tag("127.0.0.1", clientPort, Collections.singletonList(tlv2)); response = client.newRequest("localhost", serverPort) .tag(tag2) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); // Make sure the two TLVs created two destinations. assertEquals(2, client.getDestinations().size()); } @Test public void testProxyProtocolWrappingHTTPProxy() throws Exception { startServer(new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(MimeTypes.Type.TEXT_PLAIN.asString()); response.getOutputStream().print(request.getRemotePort()); } }); startClient(); int proxyPort = connector.getLocalPort(); int serverPort = proxyPort + 1; // Any port will do. client.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort)); // We are simulating to be a HttpClient inside a proxy. // The server is configured with the PROXY protocol to know the socket address of clients. // The proxy receives a request from the client, and it extracts the client address. int clientPort = ThreadLocalRandom.current().nextInt(1024, 65536); V1.Tag tag = new V1.Tag("127.0.0.1", clientPort); // The proxy maps the client address, then sends the request. ContentResponse response = client.newRequest("localhost", serverPort) .tag(tag) .header(HttpHeader.CONNECTION, "close") .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); List<Destination> destinations = client.getDestinations(); assertEquals(1, destinations.size()); HttpDestination destination = (HttpDestination)destinations.get(0); assertTrue(destination.getConnectionPool().isEmpty()); // The previous connection has been closed. // Make another request from the same client address. response = client.newRequest("localhost", serverPort) .tag(tag) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort), response.getContentAsString()); destinations = client.getDestinations(); assertEquals(1, destinations.size()); assertSame(destination, destinations.get(0)); // Make another request from a different client address. int clientPort2 = clientPort + 1; V1.Tag tag2 = new V1.Tag("127.0.0.1", clientPort2); response = client.newRequest("localhost", serverPort) .tag(tag2) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); assertEquals(String.valueOf(clientPort2), response.getContentAsString()); destinations = client.getDestinations(); assertEquals(2, destinations.size()); } }
/* * Copyright (c) 2016 droidwolf(droidwolf2006@gmail.com) * 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 com.helloworld; import android.app.Application; import com.facebook.infer.annotation.Assertions; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.common.LifecycleState; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected ReactInstanceManager createReactInstanceManager() { ReactInstanceManager.Builder builder = ReactInstanceManager.builder() .setApplication(MainApplication.this) .setJSMainModuleName(getJSMainModuleName()) .setUseDeveloperSupport(getUseDeveloperSupport()) .setUIImplementationProvider(new MyUIImplementationProvider()) .setInitialLifecycleState(LifecycleState.BEFORE_CREATE); for (ReactPackage reactPackage : getPackages()) { builder.addPackage(reactPackage); } String jsBundleFile = getJSBundleFile(); if (jsBundleFile != null) { builder.setJSBundleFile(jsBundleFile); } else { builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName())); } return builder.build(); } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new MyReactPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } }
public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } }
package com.elifut.models; import android.os.Parcelable; import android.support.annotation.Nullable; import com.google.auto.value.AutoValue; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import org.apache.commons.math3.distribution.NormalDistribution; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.schedulers.Schedulers; @AutoValue public abstract class MatchResult implements Parcelable, Persistable { public static final float HOME_WIN_PROBABILITY = .465f; public static final float DRAW_PROBABILITY = .174f; public static final NormalDistribution GOALS_DISTRIBUTION = new NormalDistribution(2.6, 1.7); @Nullable public abstract Club winner(); @Nullable public abstract Club loser(); public abstract boolean isDraw(); public abstract boolean isHomeWin(); public abstract boolean isAwayWin(); public abstract List<Goal> homeGoals(); public abstract List<Goal> awayGoals(); public abstract String finalScore(); @AutoValue.Builder public abstract static class Builder { public abstract Builder homeGoals(List<Goal> x); public abstract Builder awayGoals(List<Goal> x); abstract MatchResult autoBuild(); abstract Builder winner(Club x); abstract Builder loser(Club x); abstract Builder isDraw(boolean x); abstract Builder isHomeWin(boolean x); abstract Builder isAwayWin(boolean x); abstract Builder finalScore(String x); abstract List<Goal> homeGoals(); abstract List<Goal> awayGoals(); public MatchResult build(Club home, Club away) { Club winner = null; Club loser = null; boolean isDraw = false; boolean isHomeWin = false; boolean isAwayWin = false; int awayGoals = awayGoals().size(); int homeGoals = homeGoals().size(); if (homeGoals != awayGoals) { winner = homeGoals > awayGoals ? home : away; loser = homeGoals > awayGoals ? away : home; isHomeWin = homeGoals > awayGoals; isAwayWin = !isHomeWin; } else { isDraw = true; } return winner(winner) .loser(loser) .isDraw(isDraw) .isHomeWin(isHomeWin) .isAwayWin(isAwayWin) .finalScore(homeGoals + "x" + awayGoals) .autoBuild(); } } public static Builder builder() { return new AutoValue_MatchResult.Builder() .homeGoals(Collections.emptyList()) .awayGoals(Collections.emptyList()) .isHomeWin(false) .isAwayWin(false) .isDraw(false); } @Override public int describeContents() { return 0; } public static JsonAdapter<MatchResult> jsonAdapter(Moshi moshi) { return new AutoValue_MatchResult.MoshiJsonAdapter(moshi); } /** * Returns an {@link Observable} that emits the all the {@link MatchEvent} of this result in this * match at the correct time that they happened. */ public Observable<MatchEvent> eventsObservable(final int elapsedTime, int gameSpeed) { Observable<Goal> homeGoalsObservable = Observable.from(homeGoals()); Observable<Goal> awayGoalsObservable = Observable.from(awayGoals()); return Observable.merge(homeGoalsObservable, awayGoalsObservable) .observeOn(Schedulers.io()) .flatMap((goal) -> Observable.<MatchEvent>just(goal) .delay((1000 * goal.time()) / gameSpeed, TimeUnit.MILLISECONDS) .skip((1000 * elapsedTime) / gameSpeed, TimeUnit.MILLISECONDS)); } }
package org.cloudfoundry.autoscaler.data.couchdb.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.cloudfoundry.autoscaler.data.couchdb.dao.ScalingHistoryDAO; import org.cloudfoundry.autoscaler.data.couchdb.dao.base.TypedCouchDbRepositorySupport; import org.cloudfoundry.autoscaler.data.couchdb.document.ScalingHistory; import org.ektorp.ComplexKey; import org.ektorp.CouchDbConnector; import org.ektorp.ViewQuery; import org.ektorp.support.View; public class ScalingHistoryDAOImpl extends CommonDAOImpl implements ScalingHistoryDAO { @View(name = "byAll", map = "function(doc) { if (doc.type == 'ScalingHistory' ) emit( [doc.appId, doc.status], doc._id )}") public class ScalingHistoryRepository_All extends TypedCouchDbRepositorySupport<ScalingHistory> { public ScalingHistoryRepository_All(CouchDbConnector db) { super(ScalingHistory.class, db, "ScalingHistory_byAll"); } public List<ScalingHistory> getAllRecords() { return queryView("byAll"); } } @View(name = "findByScalingTime", map = "function(doc) { if (doc.type == 'ScalingHistory' && doc.appId &&doc.startTime" + ") emit( [doc.appId, doc.startTime], doc._id )}") public class ScalingHistoryRepository_ByScalingTime extends TypedCouchDbRepositorySupport<ScalingHistory> { public ScalingHistoryRepository_ByScalingTime(CouchDbConnector db) { super(ScalingHistory.class, db, "ScalingHistory_ByScalingTime"); } public List<ScalingHistory> findByScalingTime(String appId, long startTime, long endTime) { ComplexKey startKey = ComplexKey.of(appId, endTime); ComplexKey endKey = ComplexKey.of(appId, startTime); ViewQuery q = createQuery("findByScalingTime").includeDocs(true).startKey(startKey).endKey(endKey) .descending(true); List<ScalingHistory> returnvalue = null; String[] input = beforeConnection("QUERY", new String[] { "findByScalingTime", appId, String.valueOf(startTime), String.valueOf(endTime) }); try { returnvalue = db.queryView(q, ScalingHistory.class); } catch (Exception e) { e.printStackTrace(); } afterConnection(input); return returnvalue; } } private static final Logger logger = Logger.getLogger(ScalingHistoryDAOImpl.class); private ScalingHistoryRepository_All scalingHistoryAllRepo = null; private ScalingHistoryRepository_ByScalingTime scalingHistoryByScalingTimeRepo = null; public ScalingHistoryDAOImpl(CouchDbConnector db) { this.scalingHistoryAllRepo = new ScalingHistoryRepository_All(db); this.scalingHistoryByScalingTimeRepo = new ScalingHistoryRepository_ByScalingTime(db); } public ScalingHistoryDAOImpl(CouchDbConnector db, boolean initDesignDocument) { this(db); if (initDesignDocument) { try { initAllRepos(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } @Override public List<ScalingHistory> findAll() { // TODO Auto-generated method stub return this.scalingHistoryAllRepo.getAllRecords(); } @Override public List<ScalingHistory> findByScalingTime(String appId, long startTime, long endTime) { // TODO Auto-generated method stub return this.scalingHistoryByScalingTimeRepo.findByScalingTime(appId, startTime, endTime); } @SuppressWarnings("unchecked") @Override public <T> TypedCouchDbRepositorySupport<T> getDefaultRepo() { // TODO Auto-generated method stub return (TypedCouchDbRepositorySupport<T>) this.scalingHistoryAllRepo; } @SuppressWarnings("unchecked") @Override public <T> List<TypedCouchDbRepositorySupport<T>> getAllRepos() { // TODO Auto-generated method stub List<TypedCouchDbRepositorySupport<T>> repoList = new ArrayList<TypedCouchDbRepositorySupport<T>>(); repoList.add((TypedCouchDbRepositorySupport<T>) this.scalingHistoryAllRepo); repoList.add((TypedCouchDbRepositorySupport<T>) this.scalingHistoryByScalingTimeRepo); return repoList; } }
package org.ttrzcinski.interfaces; /** * Forces adding method to show properties n console. * * @author <a href="mailto:trzcinski.tomasz.1988@gmail.com">Tomasz T.</a> * @version 1.0 */ public interface I2Console { /** * Lists all properties of instance. */ void toConsole(); }
package com.WIZLights; import com.google.inject.Guice; import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import com.google.inject.testing.fieldbinder.BoundFieldModule; import javax.inject.Inject; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RunWith(MockitoJUnitRunner.class) public class UDPTest extends TestCase { @Inject private UDP udp; @Before public void setUp() { Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this); } @Test public void messageBuilderSetPilotTest() { Map<String, Integer> params = new HashMap<>(); params.put("r", 255); params.put("g", 0); params.put("b", 230); String actualMessage = udp.messageBuilder(UDP.Method.SETPILOT, params); String expectedMessage = "{\"method\":\"setPilot\",\"params\":{\"r\":255,\"b\":230,\"g\":0}}"; assertEquals(expectedMessage, actualMessage); } @Test public void messageBuilderGetPilotTest() { String actualMessage = udp.messageBuilder(UDP.Method.GETPILOT); String expectedMessage = "{\"method\":\"getPilot\"}"; assertEquals(expectedMessage, actualMessage); } @Test public void convertGetToSetPilot() { String getPilot = "{\"method\":\"getPilot\",\"env\":\"pro\",\"params\":{\"mac\":\"d8a011312d50\",\"rssi\":-58,\"state\":true,\"sceneId\":0,\"r\":255,\"g\":150,\"b\":0,\"c\":0,\"w\":0,\"dimming\":100}}"; String setPilot = udp.convertGetToSetPilot(getPilot); String expectedMessage = "{\"method\":\"setPilot\",\"env\":\"pro\",\"params\":{\"mac\":\"d8a011312d50\",\"rssi\":-58,\"state\":true,\"r\":255,\"g\":150,\"b\":0,\"c\":0,\"w\":0,\"dimming\":100}}"; assertEquals(expectedMessage, setPilot); } }
package com.github.cc3002.citricjuice.controller.states; public class BattlePhase extends TurnState { /** * change the canFight parameter for security */ public BattlePhase(){ this.canFight=true; } @Override public void toWaitFight(){this.changeTurnState(new WaitFight());} @Override public void toEndTurn(){this.changeTurnState(new EndTurn());} @Override public boolean inBattlePhase(){return true;} /** * return the name of the state * * @return String */ public String toString(){return "BattlePhase";} /** * method that handle the logic behind the battles * * @throws InvalidActionException */ public void battle() throws InvalidActionException{ super.battle(); if(gameController.getTurnOwner().getCurrentHP()>0 && gameController.getNumberOfPlayersToFight()>0){ toWaitFight(); } else{ toEndTurn(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.synapse.fluent.models.SelfHostedIntegrationRuntimeNodeInner; import com.azure.resourcemanager.synapse.models.UpdateIntegrationRuntimeNodeRequest; /** An instance of this class provides access to all the operations defined in IntegrationRuntimeNodesClient. */ public interface IntegrationRuntimeNodesClient { /** * Get an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an integration runtime node. */ @ServiceMethod(returns = ReturnType.SINGLE) SelfHostedIntegrationRuntimeNodeInner get( String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName); /** * Get an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an integration runtime node along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<SelfHostedIntegrationRuntimeNodeInner> getWithResponse( String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName, Context context); /** * Create an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @param updateIntegrationRuntimeNodeRequest The parameters for updating an integration runtime node. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return properties of Self-hosted integration runtime node. */ @ServiceMethod(returns = ReturnType.SINGLE) SelfHostedIntegrationRuntimeNodeInner update( String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName, UpdateIntegrationRuntimeNodeRequest updateIntegrationRuntimeNodeRequest); /** * Create an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @param updateIntegrationRuntimeNodeRequest The parameters for updating an integration runtime node. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return properties of Self-hosted integration runtime node along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<SelfHostedIntegrationRuntimeNodeInner> updateWithResponse( String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName, UpdateIntegrationRuntimeNodeRequest updateIntegrationRuntimeNodeRequest, Context context); /** * Delete an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName); /** * Delete an integration runtime node. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param integrationRuntimeName Integration runtime name. * @param nodeName Integration runtime node name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<Void> deleteWithResponse( String resourceGroupName, String workspaceName, String integrationRuntimeName, String nodeName, Context context); }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.10.24 at 03:44:55 PM BST // package OctopusConsortium.Models.RCS; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for POCD_MT000002UK01.Participant1 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="POCD_MT000002UK01.Participant1"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="realmCode" type="{urn:hl7-org:v3}CS" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="typeId" type="{urn:hl7-org:v3}POCD_MT000002UK01.InfrastructureRoot.typeId" minOccurs="0"/> * &lt;element name="templateId" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element ref="{NPFIT:HL7:Localisation}contentId" minOccurs="0"/> * &lt;element name="functionCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="time" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="associatedEntity" type="{urn:hl7-org:v3}POCD_MT000002UK01.AssociatedEntity"/> * &lt;/sequence> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="typeCode" use="required" type="{urn:hl7-org:v3}ParticipationType" /> * &lt;attribute name="contextControlCode" type="{urn:hl7-org:v3}ContextControl" fixed="OP" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "POCD_MT000002UK01.Participant1", propOrder = { "realmCode", "typeId", "templateId", "contentId", "functionCode", "time", "associatedEntity" }) public class POCDMT000002UK01Participant1 { protected List<CS> realmCode; protected POCDMT000002UK01InfrastructureRootTypeId typeId; protected List<II> templateId; @XmlElement(namespace = "NPFIT:HL7:Localisation") protected TemplateContent contentId; protected CE functionCode; protected IVLTS time; @XmlElement(required = true) protected POCDMT000002UK01AssociatedEntity associatedEntity; @XmlAttribute protected List<String> nullFlavor; @XmlAttribute(required = true) protected List<String> typeCode; @XmlAttribute protected List<String> contextControlCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link POCDMT000002UK01InfrastructureRootTypeId } * */ public POCDMT000002UK01InfrastructureRootTypeId getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link POCDMT000002UK01InfrastructureRootTypeId } * */ public void setTypeId(POCDMT000002UK01InfrastructureRootTypeId value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the contentId property. * * @return * possible object is * {@link TemplateContent } * */ public TemplateContent getContentId() { return contentId; } /** * Sets the value of the contentId property. * * @param value * allowed object is * {@link TemplateContent } * */ public void setContentId(TemplateContent value) { this.contentId = value; } /** * Gets the value of the functionCode property. * * @return * possible object is * {@link CE } * */ public CE getFunctionCode() { return functionCode; } /** * Sets the value of the functionCode property. * * @param value * allowed object is * {@link CE } * */ public void setFunctionCode(CE value) { this.functionCode = value; } /** * Gets the value of the time property. * * @return * possible object is * {@link IVLTS } * */ public IVLTS getTime() { return time; } /** * Sets the value of the time property. * * @param value * allowed object is * {@link IVLTS } * */ public void setTime(IVLTS value) { this.time = value; } /** * Gets the value of the associatedEntity property. * * @return * possible object is * {@link POCDMT000002UK01AssociatedEntity } * */ public POCDMT000002UK01AssociatedEntity getAssociatedEntity() { return associatedEntity; } /** * Sets the value of the associatedEntity property. * * @param value * allowed object is * {@link POCDMT000002UK01AssociatedEntity } * */ public void setAssociatedEntity(POCDMT000002UK01AssociatedEntity value) { this.associatedEntity = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the typeCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the typeCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTypeCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTypeCode() { if (typeCode == null) { typeCode = new ArrayList<String>(); } return this.typeCode; } /** * Gets the value of the contextControlCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the contextControlCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContextControlCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getContextControlCode() { if (contextControlCode == null) { contextControlCode = new ArrayList<String>(); } return this.contextControlCode; } }
package dev.xdark.ssvm.execution.rewrite; import dev.xdark.ssvm.asm.VMTypeInsnNode; import dev.xdark.ssvm.execution.ExecutionContext; import dev.xdark.ssvm.execution.InstructionProcessor; import dev.xdark.ssvm.execution.Result; /** * Fast path for CHECKCAST. */ public class VMCastProcessor implements InstructionProcessor<VMTypeInsnNode> { @Override public Result execute(VMTypeInsnNode insn, ExecutionContext ctx) { ctx.getOperations().checkCast(ctx.getStack().peek(), insn.getJavaType()); return Result.CONTINUE; } }
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.soytree; import static com.google.template.soy.soytree.TemplateSubject.assertThatTemplateContent; import com.google.template.soy.exprparse.ExpressionParser; import junit.framework.TestCase; /** * Tests for {@link ForNode}. * * @author brndn@google.com (Brendan Linn) */ public final class ForNodeTest extends TestCase { public void testInvalidRangeInFor() { assertThatTemplateContent("{for $x in range()}{/for}\n") .causesError(ExpressionParser.INVALID_EXPRESSION_LIST) .at(1, 1); // ForNodes don't have accurate source location information for their command texts yet. // TODO(user): fix. assertThatTemplateContent("{for $x in range()}{/for}") .causesError(ExpressionParser.INVALID_EXPRESSION_LIST) .at(1, 1); assertThatTemplateContent("{for\n\n\n\n$x in range()}{/for}") .causesError(ExpressionParser.INVALID_EXPRESSION_LIST) .at(1, 1); } }
/* Copyright 2015-2017 Artem Stasiuk Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.github.terma.fastselect; import com.github.terma.fastselect.data.MultiLongData; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class MultiLongRequestTest { private MultiLongData data; private FastSelect.Column column; private static MultiLongRequest createRequest(FastSelect.Column column, long... values) { MultiLongRequest request = new MultiLongRequest("x", values); Map<String, FastSelect.Column> columnsByNames = new HashMap<>(); columnsByNames.put("x", column); request.prepare(columnsByNames); return request; } @Before public void init() { column = new FastSelect.Column("x", long[].class, 100); data = (MultiLongData) column.data; } @Test public void acceptValues() { data.add(new long[]{Long.MAX_VALUE}); data.add(new long[]{6}); MultiLongRequest request = createRequest(column, Long.MAX_VALUE); Assert.assertTrue(request.checkValue(0)); Assert.assertFalse(request.checkValue(1)); } @Test public void acceptValuesWhenArraysAreEquals() { data.add(new long[]{Long.MIN_VALUE, 10}); data.add(new long[]{6}); MultiLongRequest request = createRequest(column, Long.MIN_VALUE, 10); Assert.assertTrue(request.checkValue(0)); Assert.assertFalse(request.checkValue(1)); } @Test public void acceptOnlyWhenAtLeastOneElementEquals() { data.add(new long[]{Long.MIN_VALUE, 10}); data.add(new long[]{6}); MultiLongRequest request = createRequest(column, Long.MIN_VALUE, -1); Assert.assertTrue(request.checkValue(0)); Assert.assertFalse(request.checkValue(1)); } @Test public void nothingAcceptIfNoRequestValues() { data.add(new long[]{Short.MIN_VALUE, 10}); data.add(new long[]{6}); MultiLongRequest request = createRequest(column); Assert.assertFalse(request.checkValue(0)); Assert.assertFalse(request.checkValue(1)); } @Test public void checkBlocksAlwaysTrue() { MultiLongRequest request = createRequest(column); Assert.assertTrue(request.checkBlock(null)); } @Test public void provideToString() { MultiLongRequest request = createRequest(column, Long.MIN_VALUE, Long.MAX_VALUE); Assert.assertEquals("MultiLongRequest {name: 'x', values: [-9223372036854775808, 9223372036854775807]}", request.toString()); } }
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.onnx; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.onnx.global.onnx.*; @Properties(inherit = org.bytedeco.onnx.presets.onnx.class) public class onnxReleaseBackendFunction extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public onnxReleaseBackendFunction(Pointer p) { super(p); } protected onnxReleaseBackendFunction() { allocate(); } private native void allocate(); public native @Cast("onnxStatus") int call( onnxBackend backend); }
/* * Copyright (c) 2007 Sun Microsystems, 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: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * */ // MainFrame - run an Applet as an application // // Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. 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 THE AUTHOR 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 AUTHOR 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. // // Visit the ACME Labs Java page for up-to-date versions of this and other // fine Java utilities: http://www.acme.com/java/ // --------------------------------------------------------------------- package com.sun.j3d.utils.applet; import java.applet.Applet; import java.applet.AppletContext; import java.applet.AppletStub; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.Image; import java.awt.Label; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.ImageProducer; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; /// Run an Applet as an application. // <P> // Using this class you can add a trivial main program to any Applet // and run it directly, as well as from a browser or the appletviewer. // And unlike some versions of this concept, MainFrame implements both // images and sound. // <P> // Sample main program: // <BLOCKQUOTE><PRE> // public static void main( String[] args ) // { // new Acme.MainFrame( new ThisApplet(), args, 400, 400 ); // } // </PRE></BLOCKQUOTE> // The only methods you need to know about are the constructors. // <P> // You can specify Applet parameters on the command line, as name=value. // For instance, the equivalent of: // <BLOCKQUOTE><PRE> // &lt;PARAM NAME="pause" VALUE="200"&gt; // </PRE></BLOCKQUOTE> // would just be: // <BLOCKQUOTE><PRE> // pause=200 // </PRE></BLOCKQUOTE> // You can also specify three special parameters: // <BLOCKQUOTE><PRE> // width=N Width of the Applet. // height=N Height of the Applet. // barebones=true Leave off the menu bar and status area. // </PRE></BLOCKQUOTE> // <P> // <A HREF="/resources/classes/Acme/MainFrame.java">Fetch the software.</A><BR> // <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A> public class MainFrame extends Frame implements Runnable, AppletStub, AppletContext { private String[] args = null; private static int instances = 0; private String name; private boolean barebones = true; private Applet applet; private Label label = null; private Dimension appletSize; private static final String PARAM_PROP_PREFIX = "parameter."; /// Constructor with everything specified. public MainFrame(Applet applet, String[] args, int width, int height) { build(applet, args, width, height); } /// Constructor with no default width/height. public MainFrame(Applet applet, String[] args ) { build(applet, args, -1, -1); } /// Constructor with no arg parsing. public MainFrame(Applet applet, int width, int height) { build( applet, null, width, height ); } // Internal constructor routine. private void build( Applet applet, String[] args, int width, int height) { ++instances; this.applet = applet; this.args = args; applet.setStub( this ); name = applet.getClass().getName(); setTitle( name ); // Set up properties. Properties props = System.getProperties(); props.put( "browser", "Acme.MainFrame" ); props.put( "browser.version", "11jul96" ); props.put( "browser.vendor", "Acme Laboratories" ); props.put( "browser.vendor.url", "http://www.acme.com/" ); // Turn args into parameters by way of the properties list. if ( args != null ) parseArgs( args, props ); // If width and height are specified in the parameters, override // the compiled-in values. String widthStr = getParameter( "width" ); if ( widthStr != null ) { width = Integer.parseInt( widthStr ); } String heightStr = getParameter( "height" ); if ( heightStr != null ) { height = Integer.parseInt( heightStr ); } // Were width and height specified somewhere? if ((width == -1) || (height == -1)) { System.err.println( "Width and height must be specified." ); return; } // Do we want to run bare-bones? String bonesStr = getParameter( "barebones" ); if ((bonesStr != null) && bonesStr.equals( "true" )) { barebones = true; } // Lay out components. setLayout( new BorderLayout() ); add( "Center", applet ); // Set up size. pack(); validate(); appletSize = applet.getSize(); applet.setSize( width, height ); setVisible(true); /* Added WindowListener inner class to detect close events. */ SecurityManager sm = System.getSecurityManager(); boolean doExit = true; if (sm != null) { try { sm.checkExit(0); } catch (SecurityException e) { doExit = false; } } final boolean _doExit = doExit; addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent winEvent) { if (MainFrame.this.applet != null) { MainFrame.this.applet.destroy(); } Window w = winEvent.getWindow(); w.hide(); try { w.dispose(); } catch (IllegalStateException e) {} if (_doExit) { System.exit(0); } } }); // Start a separate thread to call the applet's init() and start() // methods, in case they take a long time. (new Thread( this )).start(); } // Turn command-line arguments into Applet parameters, by way of the // properties list. private static void parseArgs( String[] args, Properties props) { String arg; for (int i = 0; i < args.length; ++i) { arg = args[i]; int ind = arg.indexOf( '=' ); if ( ind == -1 ) { props.put(PARAM_PROP_PREFIX + arg.toLowerCase(), "" ); } else { props.put(PARAM_PROP_PREFIX + arg.substring( 0, ind ).toLowerCase(), arg.substring( ind + 1 ) ); } } } // Methods from Runnable. /// Separate thread to call the applet's init() and start() methods. public void run() { showStatus( name + " initializing..." ); applet.init(); validate(); showStatus( name + " starting..." ); applet.start(); validate(); showStatus( name + " running..." ); } // Methods from AppletStub. public boolean isActive() { return true; } public URL getDocumentBase() { // Returns the current directory. String dir = System.getProperty( "user.dir" ); String urlDir = dir.replace( File.separatorChar, '/' ); try { return new URL( "file:" + urlDir + "/"); } catch ( MalformedURLException e ) { return null; } } public URL getCodeBase() { // Hack: loop through each item in CLASSPATH, checking if // the appropriately named .class file exists there. But // this doesn't account for .zip files. String path = System.getProperty( "java.class.path" ); Enumeration st = new StringTokenizer( path, ":" ); while ( st.hasMoreElements() ) { String dir = (String) st.nextElement(); String filename = dir + File.separatorChar + name + ".class"; File file = new File( filename ); if (file.exists()) { String urlDir = dir.replace( File.separatorChar, '/' ); try { return new URL( "file:" + urlDir + "/" ); } catch (MalformedURLException e) { return null; } } } return null; } public String getParameter(String name) { // Return a parameter via the munged names in the properties list. return System.getProperty( PARAM_PROP_PREFIX + name.toLowerCase() ); } public void appletResize(int width, int height) { // Change the frame's size by the same amount that the applet's // size is changing. Dimension frameSize = getSize(); frameSize.width += width - appletSize.width; frameSize.height += height - appletSize.height; setSize( frameSize ); appletSize = applet.getSize(); } public AppletContext getAppletContext() { return this; } // Methods from AppletContext. public AudioClip getAudioClip( URL url ) { // This is an internal undocumented routine. However, it // also provides needed functionality not otherwise available. // I suspect that in a future release, JavaSoft will add an // audio content handler which encapsulates this, and then // we can just do a getContent just like for images. return new sun.applet.AppletAudioClip( url ); } public Image getImage( URL url ) { Toolkit tk = Toolkit.getDefaultToolkit(); try { ImageProducer prod = (ImageProducer) url.getContent(); return tk.createImage( prod ); } catch ( IOException e ) { return null; } } public Applet getApplet(String name) { // Returns this Applet or nothing. if (name.equals( this.name )) { return applet; } return null; } public Enumeration getApplets() { // Just yields this applet. Vector v = new Vector(); v.addElement( applet ); return v.elements(); } public void showDocument( URL url ) { // Ignore. } public void showDocument( URL url, String target ) { // Ignore. } public void showStatus( String status ) { if (label != null) { label.setText(status); } } public void setStream( String key, java.io.InputStream stream ) { throw new RuntimeException("Not Implemented"); // TODO implement setStream method } public java.io.InputStream getStream( String key ) { throw new RuntimeException("Not Implemented"); // TODO implement getStream method } public java.util.Iterator getStreamKeys() { throw new RuntimeException("Not Implemented"); // TODO implement getStreamKeys method } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.security; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION; import static org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.*; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import javax.security.auth.kerberos.KerberosPrincipal; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; public class TestSecurityUtil { @BeforeClass public static void unsetKerberosRealm() { // prevent failures if kinit-ed or on os x with no realm System.setProperty("java.security.krb5.kdc", ""); System.setProperty("java.security.krb5.realm", "NONE"); } @Test public void isOriginalTGTReturnsCorrectValues() { assertTrue(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/foo@foo"))); assertTrue(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/foo.bar.bat@foo.bar.bat"))); assertFalse(SecurityUtil.isTGSPrincipal (null)); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("blah"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal(""))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/hello"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("/@"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/foo@FOO"))); } private void verify(String original, String hostname, String expected) throws IOException { assertEquals(expected, SecurityUtil.getServerPrincipal(original, hostname)); InetAddress addr = mockAddr(hostname); assertEquals(expected, SecurityUtil.getServerPrincipal(original, addr)); } private InetAddress mockAddr(String reverseTo) { InetAddress mock = Mockito.mock(InetAddress.class); Mockito.doReturn(reverseTo).when(mock).getCanonicalHostName(); return mock; } @Test public void testGetServerPrincipal() throws IOException { String service = "hdfs/"; String realm = "@REALM"; String hostname = "foohost"; String userPrincipal = "foo@FOOREALM"; String shouldReplace = service + SecurityUtil.HOSTNAME_PATTERN + realm; String replaced = service + hostname + realm; verify(shouldReplace, hostname, replaced); String shouldNotReplace = service + SecurityUtil.HOSTNAME_PATTERN + "NAME" + realm; verify(shouldNotReplace, hostname, shouldNotReplace); verify(userPrincipal, hostname, userPrincipal); // testing reverse DNS lookup doesn't happen InetAddress notUsed = Mockito.mock(InetAddress.class); assertEquals(shouldNotReplace, SecurityUtil.getServerPrincipal(shouldNotReplace, notUsed)); Mockito.verify(notUsed, Mockito.never()).getCanonicalHostName(); } @Test public void testPrincipalsWithLowerCaseHosts() throws IOException { String service = "xyz/"; String realm = "@REALM"; String principalInConf = service + SecurityUtil.HOSTNAME_PATTERN + realm; String hostname = "FooHost"; String principal = service + hostname.toLowerCase() + realm; verify(principalInConf, hostname, principal); } @Test public void testLocalHostNameForNullOrWild() throws Exception { String local = SecurityUtil.getLocalHostName(); assertEquals("hdfs/" + local + "@REALM", SecurityUtil.getServerPrincipal("hdfs/_HOST@REALM", (String)null)); assertEquals("hdfs/" + local + "@REALM", SecurityUtil.getServerPrincipal("hdfs/_HOST@REALM", "0.0.0.0")); } @Test public void testStartsWithIncorrectSettings() throws IOException { Configuration conf = new Configuration(); SecurityUtil.setAuthenticationMethod(KERBEROS, conf); String keyTabKey="key"; conf.set(keyTabKey, ""); UserGroupInformation.setConfiguration(conf); boolean gotException = false; try { SecurityUtil.login(conf, keyTabKey, "", ""); } catch (IOException e) { // expected gotException=true; } assertTrue("Exception for empty keytabfile name was expected", gotException); } @Test public void testGetHostFromPrincipal() { assertEquals("host", SecurityUtil.getHostFromPrincipal("service/host@realm")); assertEquals(null, SecurityUtil.getHostFromPrincipal("service@realm")); } @Test public void testBuildDTServiceName() { SecurityUtil.setTokenServiceUseIp(true); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test://LocalHost"), 123) ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test://LocalHost:123"), 456) ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test://127.0.0.1"), 123) ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test://127.0.0.1:123"), 456) ); } @Test public void testBuildTokenServiceSockAddr() { SecurityUtil.setTokenServiceUseIp(true); assertEquals("127.0.0.1:123", SecurityUtil.buildTokenService(new InetSocketAddress("LocalHost", 123)).toString() ); assertEquals("127.0.0.1:123", SecurityUtil.buildTokenService(new InetSocketAddress("127.0.0.1", 123)).toString() ); // what goes in, comes out assertEquals("127.0.0.1:123", SecurityUtil.buildTokenService(NetUtils.createSocketAddr("127.0.0.1", 123)).toString() ); } @Test public void testGoodHostsAndPorts() { InetSocketAddress compare = NetUtils.createSocketAddrForHost("localhost", 123); runGoodCases(compare, "localhost", 123); runGoodCases(compare, "localhost:", 123); runGoodCases(compare, "localhost:123", 456); } void runGoodCases(InetSocketAddress addr, String host, int port) { assertEquals(addr, NetUtils.createSocketAddr(host, port)); assertEquals(addr, NetUtils.createSocketAddr("hdfs://"+host, port)); assertEquals(addr, NetUtils.createSocketAddr("hdfs://"+host+"/path", port)); } @Test public void testBadHostsAndPorts() { runBadCases("", true); runBadCases(":", false); runBadCases("hdfs/", false); runBadCases("hdfs:/", false); runBadCases("hdfs://", true); } void runBadCases(String prefix, boolean validIfPosPort) { runBadPortPermutes(prefix, false); runBadPortPermutes(prefix+"*", false); runBadPortPermutes(prefix+"localhost", validIfPosPort); runBadPortPermutes(prefix+"localhost:-1", false); runBadPortPermutes(prefix+"localhost:-123", false); runBadPortPermutes(prefix+"localhost:xyz", false); runBadPortPermutes(prefix+"localhost/xyz", validIfPosPort); runBadPortPermutes(prefix+"localhost/:123", validIfPosPort); runBadPortPermutes(prefix+":123", false); runBadPortPermutes(prefix+":xyz", false); } void runBadPortPermutes(String arg, boolean validIfPosPort) { int ports[] = { -123, -1, 123 }; boolean bad = false; try { NetUtils.createSocketAddr(arg); } catch (IllegalArgumentException e) { bad = true; } finally { assertTrue("should be bad: '"+arg+"'", bad); } for (int port : ports) { if (validIfPosPort && port > 0) continue; bad = false; try { NetUtils.createSocketAddr(arg, port); } catch (IllegalArgumentException e) { bad = true; } finally { assertTrue("should be bad: '"+arg+"' (default port:"+port+")", bad); } } } // check that the socket addr has: // 1) the InetSocketAddress has the correct hostname, ie. exact host/ip given // 2) the address is resolved, ie. has an ip // 3,4) the socket's InetAddress has the same hostname, and the correct ip // 5) the port is correct private void verifyValues(InetSocketAddress addr, String host, String ip, int port) { assertTrue(!addr.isUnresolved()); // don't know what the standard resolver will return for hostname. // should be host for host; host or ip for ip is ambiguous if (!SecurityUtil.useIpForTokenService) { assertEquals(host, addr.getHostName()); assertEquals(host, addr.getAddress().getHostName()); } assertEquals(ip, addr.getAddress().getHostAddress()); assertEquals(port, addr.getPort()); } // check: // 1) buildTokenService honors use_ip setting // 2) setTokenService & getService works // 3) getTokenServiceAddr decodes to the identical socket addr private void verifyTokenService(InetSocketAddress addr, String host, String ip, int port, boolean useIp) { //LOG.info("address:"+addr+" host:"+host+" ip:"+ip+" port:"+port); SecurityUtil.setTokenServiceUseIp(useIp); String serviceHost = useIp ? ip : host.toLowerCase(); Token<?> token = new Token<TokenIdentifier>(); Text service = new Text(serviceHost+":"+port); assertEquals(service, SecurityUtil.buildTokenService(addr)); SecurityUtil.setTokenService(token, addr); assertEquals(service, token.getService()); InetSocketAddress serviceAddr = SecurityUtil.getTokenServiceAddr(token); assertNotNull(serviceAddr); verifyValues(serviceAddr, serviceHost, ip, port); } // check: // 1) socket addr is created with fields set as expected // 2) token service with ips // 3) token service with the given host or ip private void verifyAddress(InetSocketAddress addr, String host, String ip, int port) { verifyValues(addr, host, ip, port); //LOG.info("test that token service uses ip"); verifyTokenService(addr, host, ip, port, true); //LOG.info("test that token service uses host"); verifyTokenService(addr, host, ip, port, false); } // check: // 1-4) combinations of host and port // this will construct a socket addr, verify all the fields, build the // service to verify the use_ip setting is honored, set the token service // based on addr and verify the token service is set correctly, decode // the token service and ensure all the fields of the decoded addr match private void verifyServiceAddr(String host, String ip) { InetSocketAddress addr; int port = 123; // test host, port tuple //LOG.info("test tuple ("+host+","+port+")"); addr = NetUtils.createSocketAddrForHost(host, port); verifyAddress(addr, host, ip, port); // test authority with no default port //LOG.info("test authority '"+host+":"+port+"'"); addr = NetUtils.createSocketAddr(host+":"+port); verifyAddress(addr, host, ip, port); // test authority with a default port, make sure default isn't used //LOG.info("test authority '"+host+":"+port+"' with ignored default port"); addr = NetUtils.createSocketAddr(host+":"+port, port+1); verifyAddress(addr, host, ip, port); // test host-only authority, using port as default port //LOG.info("test host:"+host+" port:"+port); addr = NetUtils.createSocketAddr(host, port); verifyAddress(addr, host, ip, port); } @Test public void testSocketAddrWithName() { String staticHost = "my"; NetUtils.addStaticResolution(staticHost, "localhost"); verifyServiceAddr("LocalHost", "127.0.0.1"); } @Test public void testSocketAddrWithIP() { verifyServiceAddr("127.0.0.1", "127.0.0.1"); } @Test public void testSocketAddrWithNameToStaticName() { String staticHost = "host1"; NetUtils.addStaticResolution(staticHost, "localhost"); verifyServiceAddr(staticHost, "127.0.0.1"); } @Test public void testSocketAddrWithNameToStaticIP() { String staticHost = "host3"; NetUtils.addStaticResolution(staticHost, "255.255.255.255"); verifyServiceAddr(staticHost, "255.255.255.255"); } // this is a bizarre case, but it's if a test tries to remap an ip address @Test public void testSocketAddrWithIPToStaticIP() { String staticHost = "1.2.3.4"; NetUtils.addStaticResolution(staticHost, "255.255.255.255"); verifyServiceAddr(staticHost, "255.255.255.255"); } @Test public void testGetAuthenticationMethod() { Configuration conf = new Configuration(); // default is simple conf.unset(HADOOP_SECURITY_AUTHENTICATION); assertEquals(SIMPLE, SecurityUtil.getAuthenticationMethod(conf)); // simple conf.set(HADOOP_SECURITY_AUTHENTICATION, "simple"); assertEquals(SIMPLE, SecurityUtil.getAuthenticationMethod(conf)); // kerberos conf.set(HADOOP_SECURITY_AUTHENTICATION, "kerberos"); assertEquals(KERBEROS, SecurityUtil.getAuthenticationMethod(conf)); // bad value conf.set(HADOOP_SECURITY_AUTHENTICATION, "kaboom"); String error = null; try { SecurityUtil.getAuthenticationMethod(conf); } catch (Exception e) { error = e.toString(); } assertEquals("java.lang.IllegalArgumentException: " + "Invalid attribute value for " + HADOOP_SECURITY_AUTHENTICATION + " of kaboom", error); } @Test public void testSetAuthenticationMethod() { Configuration conf = new Configuration(); // default SecurityUtil.setAuthenticationMethod(null, conf); assertEquals("simple", conf.get(HADOOP_SECURITY_AUTHENTICATION)); // simple SecurityUtil.setAuthenticationMethod(SIMPLE, conf); assertEquals("simple", conf.get(HADOOP_SECURITY_AUTHENTICATION)); // kerberos SecurityUtil.setAuthenticationMethod(KERBEROS, conf); assertEquals("kerberos", conf.get(HADOOP_SECURITY_AUTHENTICATION)); } }
/* * The MIT License (MIT) * * Copyright (c) 2014-2019 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.takes.rs; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import lombok.EqualsAndHashCode; import lombok.ToString; import org.takes.Response; import org.takes.misc.Utf8String; /** * Response decorator, with body. * * <p>This implementation of the {@link Response} interface requires that * the {@link Response#head()} method has to be invoked before reading * from the {@code InputStream} obtained from the {@link Response#body()} * method. * * <p>The class is immutable and thread-safe. * * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @since 0.1 */ @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public final class RsWithBody extends RsWrap { /** * Constructs a {@code RsWithBody} with the specified body that will be * encoded into UTF-8 by default. * @param body Body */ public RsWithBody(final CharSequence body) { this(new RsWithStatus(HttpURLConnection.HTTP_OK), body); } /** * Constructs a {@code RsWithBody} with the specified body. * @param body Body */ public RsWithBody(final byte[] body) { this(new RsWithStatus(HttpURLConnection.HTTP_OK), body); } /** * Constructs a {@code RsWithBody} with the specified body. * @param body Body */ public RsWithBody(final InputStream body) { this(new RsWithStatus(HttpURLConnection.HTTP_OK), body); } /** * Constructs a {@code RsWithBody} with the content located at the specified * url as body. * @param url URL with body */ public RsWithBody(final URL url) { this(new RsWithStatus(HttpURLConnection.HTTP_OK), url); } /** * Constructs a {@code RsWithBody} with the specified response and body. The * body will be encoded into UTF-8 by default. * @param res Original response * @param body Body */ public RsWithBody(final Response res, final CharSequence body) { this(res, new Utf8String(body.toString()).asBytes()); } /** * Constructs a {@code RsWithBody} with the specified response and body. The * body will be encoded using the specified character set. * @param res Original response * @param body Body * @param charset The character set to use to serialize the body */ public RsWithBody(final Response res, final CharSequence body, final Charset charset) { this(res, body.toString().getBytes(charset)); } /** * Ctor. * @param res Original response * @param url URL with body */ public RsWithBody(final Response res, final URL url) { this(res, new Body.Url(url)); } /** * Ctor. * @param res Original response * @param body Body */ public RsWithBody(final Response res, final byte[] body) { this(res, new Body.ByteArray(body)); } /** * Ctor. * @param res Original response * @param body Body */ public RsWithBody(final Response res, final InputStream body) { this(res, new Body.Stream(body)); } /** * Constructs a {@code RsWithBody} with the specified response and body * content. * @param res Original response * @param body The content of the body */ RsWithBody(final Response res, final Body body) { super( new Response() { @Override public Iterable<String> head() throws IOException { return RsWithBody.append(res, body.length()); } @Override public InputStream body() throws IOException { return body.stream(); } } ); } /** * Appends content length to header from response. * @param res Response * @param length Response body content length * @return Iterable String of header attributes * @throws IOException if something goes wrong. */ private static Iterable<String> append(final Response res, final int length) throws IOException { final String header = "Content-Length"; return new RsWithHeader( new RsWithoutHeader(res, header), header, Integer.toString(length) ).head(); } }
/* * Copyright (C) 2013 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.media; import android.annotation.UnsupportedAppUsage; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.graphics.Bitmap; import android.media.session.MediaController; import android.media.session.MediaSession; import android.media.session.MediaSessionLegacyHelper; import android.media.session.MediaSessionManager; import android.media.session.PlaybackState; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.UserHandle; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import java.util.List; /** * The RemoteController class is used to control media playback, display and update media metadata * and playback status, published by applications using the {@link RemoteControlClient} class. * <p> * A RemoteController shall be registered through * {@link AudioManager#registerRemoteController(RemoteController)} in order for the system to send * media event updates to the {@link OnClientUpdateListener} listener set in the class constructor. * Implement the methods of the interface to receive the information published by the active * {@link RemoteControlClient} instances. * <br>By default an {@link OnClientUpdateListener} implementation will not receive bitmaps for * album art. Use {@link #setArtworkConfiguration(int, int)} to receive images as well. * <p> * Registration requires the {@link OnClientUpdateListener} listener to be one of the enabled * notification listeners (see {@link android.service.notification.NotificationListenerService}). * * @deprecated Use {@link MediaController} instead. */ @Deprecated public final class RemoteController { private final static int MAX_BITMAP_DIMENSION = 512; private final static String TAG = "RemoteController"; private final static boolean DEBUG = false; private final static Object mInfoLock = new Object(); private final Context mContext; private final int mMaxBitmapDimension; private MetadataEditor mMetadataEditor; private MediaSessionManager mSessionManager; private MediaSessionManager.OnActiveSessionsChangedListener mSessionListener; private MediaController.Callback mSessionCb = new MediaControllerCallback(); /** * Synchronized on mInfoLock */ private boolean mIsRegistered = false; private OnClientUpdateListener mOnClientUpdateListener; private PlaybackInfo mLastPlaybackInfo; private int mArtworkWidth = -1; private int mArtworkHeight = -1; private boolean mEnabled = true; // synchronized on mInfoLock, for USE_SESSION apis. @UnsupportedAppUsage private MediaController mCurrentSession; /** * Class constructor. * @param context the {@link Context}, must be non-null. * @param updateListener the listener to be called whenever new client information is available, * must be non-null. * @throws IllegalArgumentException */ public RemoteController(Context context, OnClientUpdateListener updateListener) throws IllegalArgumentException { this(context, updateListener, null); } /** * Class constructor. * @param context the {@link Context}, must be non-null. * @param updateListener the listener to be called whenever new client information is available, * must be non-null. * @param looper the {@link Looper} on which to run the event loop, * or null to use the current thread's looper. * @throws java.lang.IllegalArgumentException */ public RemoteController(Context context, OnClientUpdateListener updateListener, Looper looper) throws IllegalArgumentException { if (context == null) { throw new IllegalArgumentException("Invalid null Context"); } if (updateListener == null) { throw new IllegalArgumentException("Invalid null OnClientUpdateListener"); } if (looper != null) { mEventHandler = new EventHandler(this, looper); } else { Looper l = Looper.myLooper(); if (l != null) { mEventHandler = new EventHandler(this, l); } else { throw new IllegalArgumentException("Calling thread not associated with a looper"); } } mOnClientUpdateListener = updateListener; mContext = context; mSessionManager = (MediaSessionManager) context .getSystemService(Context.MEDIA_SESSION_SERVICE); mSessionListener = new TopTransportSessionListener(); if (ActivityManager.isLowRamDeviceStatic()) { mMaxBitmapDimension = MAX_BITMAP_DIMENSION; } else { final DisplayMetrics dm = context.getResources().getDisplayMetrics(); mMaxBitmapDimension = Math.max(dm.widthPixels, dm.heightPixels); } } /** * Interface definition for the callbacks to be invoked whenever media events, metadata * and playback status are available. */ public interface OnClientUpdateListener { /** * Called whenever all information, previously received through the other * methods of the listener, is no longer valid and is about to be refreshed. * This is typically called whenever a new {@link RemoteControlClient} has been selected * by the system to have its media information published. * @param clearing true if there is no selected RemoteControlClient and no information * is available. */ public void onClientChange(boolean clearing); /** * Called whenever the playback state has changed. * It is called when no information is known about the playback progress in the media and * the playback speed. * @param state one of the playback states authorized * in {@link RemoteControlClient#setPlaybackState(int)}. */ public void onClientPlaybackStateUpdate(int state); /** * Called whenever the playback state has changed, and playback position * and speed are known. * @param state one of the playback states authorized * in {@link RemoteControlClient#setPlaybackState(int)}. * @param stateChangeTimeMs the system time at which the state change was reported, * expressed in ms. Based on {@link android.os.SystemClock#elapsedRealtime()}. * @param currentPosMs a positive value for the current media playback position expressed * in ms, a negative value if the position is temporarily unknown. * @param speed a value expressed as a ratio of 1x playback: 1.0f is normal playback, * 2.0f is 2x, 0.5f is half-speed, -2.0f is rewind at 2x speed. 0.0f means nothing is * playing (e.g. when state is {@link RemoteControlClient#PLAYSTATE_ERROR}). */ public void onClientPlaybackStateUpdate(int state, long stateChangeTimeMs, long currentPosMs, float speed); /** * Called whenever the transport control flags have changed. * @param transportControlFlags one of the flags authorized * in {@link RemoteControlClient#setTransportControlFlags(int)}. */ public void onClientTransportControlUpdate(int transportControlFlags); /** * Called whenever new metadata is available. * See the {@link MediaMetadataEditor#putLong(int, long)}, * {@link MediaMetadataEditor#putString(int, String)}, * {@link MediaMetadataEditor#putBitmap(int, Bitmap)}, and * {@link MediaMetadataEditor#putObject(int, Object)} methods for the various keys that * can be queried. * @param metadataEditor the container of the new metadata. */ public void onClientMetadataUpdate(MetadataEditor metadataEditor); }; /** * Return the estimated playback position of the current media track or a negative value * if not available. * * <p>The value returned is estimated by the current process and may not be perfect. * The time returned by this method is calculated from the last state change time based * on the current play position at that time and the last known playback speed. * An application may call {@link #setSynchronizationMode(int)} to apply * a synchronization policy that will periodically re-sync the estimated position * with the RemoteControlClient.</p> * * @return the current estimated playback position in milliseconds or a negative value * if not available * * @see OnClientUpdateListener#onClientPlaybackStateUpdate(int, long, long, float) */ public long getEstimatedMediaPosition() { synchronized (mInfoLock) { if (mCurrentSession != null) { PlaybackState state = mCurrentSession.getPlaybackState(); if (state != null) { return state.getPosition(); } } } return -1; } /** * Send a simulated key event for a media button to be received by the current client. * To simulate a key press, you must first send a KeyEvent built with * a {@link KeyEvent#ACTION_DOWN} action, then another event with the {@link KeyEvent#ACTION_UP} * action. * <p>The key event will be sent to the registered receiver * (see {@link AudioManager#registerMediaButtonEventReceiver(PendingIntent)}) whose associated * {@link RemoteControlClient}'s metadata and playback state is published (there may be * none under some circumstances). * @param keyEvent a {@link KeyEvent} instance whose key code is one of * {@link KeyEvent#KEYCODE_MUTE}, * {@link KeyEvent#KEYCODE_HEADSETHOOK}, * {@link KeyEvent#KEYCODE_MEDIA_PLAY}, * {@link KeyEvent#KEYCODE_MEDIA_PAUSE}, * {@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE}, * {@link KeyEvent#KEYCODE_MEDIA_STOP}, * {@link KeyEvent#KEYCODE_MEDIA_NEXT}, * {@link KeyEvent#KEYCODE_MEDIA_PREVIOUS}, * {@link KeyEvent#KEYCODE_MEDIA_REWIND}, * {@link KeyEvent#KEYCODE_MEDIA_RECORD}, * {@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD}, * {@link KeyEvent#KEYCODE_MEDIA_CLOSE}, * {@link KeyEvent#KEYCODE_MEDIA_EJECT}, * or {@link KeyEvent#KEYCODE_MEDIA_AUDIO_TRACK}. * @return true if the event was successfully sent, false otherwise. * @throws IllegalArgumentException */ public boolean sendMediaKeyEvent(KeyEvent keyEvent) throws IllegalArgumentException { if (!KeyEvent.isMediaSessionKey(keyEvent.getKeyCode())) { throw new IllegalArgumentException("not a media key event"); } synchronized (mInfoLock) { if (mCurrentSession != null) { return mCurrentSession.dispatchMediaButtonEvent(keyEvent); } return false; } } /** * Sets the new playback position. * This method can only be called on a registered RemoteController. * @param timeMs a 0 or positive value for the new playback position, expressed in ms. * @return true if the command to set the playback position was successfully sent. * @throws IllegalArgumentException */ public boolean seekTo(long timeMs) throws IllegalArgumentException { if (!mEnabled) { Log.e(TAG, "Cannot use seekTo() from a disabled RemoteController"); return false; } if (timeMs < 0) { throw new IllegalArgumentException("illegal negative time value"); } synchronized (mInfoLock) { if (mCurrentSession != null) { mCurrentSession.getTransportControls().seekTo(timeMs); } } return true; } /** * @hide * @param wantBitmap * @param width * @param height * @return true if successful * @throws IllegalArgumentException */ @UnsupportedAppUsage public boolean setArtworkConfiguration(boolean wantBitmap, int width, int height) throws IllegalArgumentException { synchronized (mInfoLock) { if (wantBitmap) { if ((width > 0) && (height > 0)) { if (width > mMaxBitmapDimension) { width = mMaxBitmapDimension; } if (height > mMaxBitmapDimension) { height = mMaxBitmapDimension; } mArtworkWidth = width; mArtworkHeight = height; } else { throw new IllegalArgumentException("Invalid dimensions"); } } else { mArtworkWidth = -1; mArtworkHeight = -1; } } return true; } /** * Set the maximum artwork image dimensions to be received in the metadata. * No bitmaps will be received unless this has been specified. * @param width the maximum width in pixels * @param height the maximum height in pixels * @return true if the artwork dimension was successfully set. * @throws IllegalArgumentException */ public boolean setArtworkConfiguration(int width, int height) throws IllegalArgumentException { return setArtworkConfiguration(true, width, height); } /** * Prevents this RemoteController from receiving artwork images. * @return true if receiving artwork images was successfully disabled. */ public boolean clearArtworkConfiguration() { return setArtworkConfiguration(false, -1, -1); } /** * Default playback position synchronization mode where the RemoteControlClient is not * asked regularly for its playback position to see if it has drifted from the estimated * position. */ public static final int POSITION_SYNCHRONIZATION_NONE = 0; /** * The playback position synchronization mode where the RemoteControlClient instances which * expose their playback position to the framework, will be regularly polled to check * whether any drift has been noticed between their estimated position and the one they report. * Note that this mode should only ever be used when needing to display very accurate playback * position, as regularly polling a RemoteControlClient for its position may have an impact * on battery life (if applicable) when this query will trigger network transactions in the * case of remote playback. */ public static final int POSITION_SYNCHRONIZATION_CHECK = 1; /** * Set the playback position synchronization mode. * Must be called on a registered RemoteController. * @param sync {@link #POSITION_SYNCHRONIZATION_NONE} or {@link #POSITION_SYNCHRONIZATION_CHECK} * @return true if the synchronization mode was successfully set. * @throws IllegalArgumentException */ public boolean setSynchronizationMode(int sync) throws IllegalArgumentException { if ((sync != POSITION_SYNCHRONIZATION_NONE) && (sync != POSITION_SYNCHRONIZATION_CHECK)) { throw new IllegalArgumentException("Unknown synchronization mode " + sync); } if (!mIsRegistered) { Log.e(TAG, "Cannot set synchronization mode on an unregistered RemoteController"); return false; } // deprecated, no-op return true; } /** * Creates a {@link MetadataEditor} for updating metadata values of the editable keys of * the current {@link RemoteControlClient}. * This method can only be called on a registered RemoteController. * @return a new MetadataEditor instance. */ public MetadataEditor editMetadata() { MetadataEditor editor = new MetadataEditor(); editor.mEditorMetadata = new Bundle(); editor.mEditorArtwork = null; editor.mMetadataChanged = true; editor.mArtworkChanged = true; editor.mEditableKeys = 0; return editor; } /** * A class to read the metadata published by a {@link RemoteControlClient}, or send a * {@link RemoteControlClient} new values for keys that can be edited. */ public class MetadataEditor extends MediaMetadataEditor { /** * @hide */ protected MetadataEditor() { } /** * @hide */ protected MetadataEditor(Bundle metadata, long editableKeys) { mEditorMetadata = metadata; mEditableKeys = editableKeys; mEditorArtwork = (Bitmap) metadata.getParcelable( String.valueOf(MediaMetadataEditor.BITMAP_KEY_ARTWORK)); if (mEditorArtwork != null) { cleanupBitmapFromBundle(MediaMetadataEditor.BITMAP_KEY_ARTWORK); } mMetadataChanged = true; mArtworkChanged = true; mApplied = false; } private void cleanupBitmapFromBundle(int key) { if (METADATA_KEYS_TYPE.get(key, METADATA_TYPE_INVALID) == METADATA_TYPE_BITMAP) { mEditorMetadata.remove(String.valueOf(key)); } } /** * Applies all of the metadata changes that have been set since the MediaMetadataEditor * instance was created with {@link RemoteController#editMetadata()} * or since {@link #clear()} was called. */ public synchronized void apply() { // "applying" a metadata bundle in RemoteController is only for sending edited // key values back to the RemoteControlClient, so here we only care about the only // editable key we support: RATING_KEY_BY_USER if (!mMetadataChanged) { return; } synchronized (mInfoLock) { if (mCurrentSession != null) { if (mEditorMetadata.containsKey( String.valueOf(MediaMetadataEditor.RATING_KEY_BY_USER))) { Rating rating = (Rating) getObject( MediaMetadataEditor.RATING_KEY_BY_USER, null); if (rating != null) { mCurrentSession.getTransportControls().setRating(rating); } } } } // NOT setting mApplied to true as this type of MetadataEditor will be applied // multiple times, whenever the user of a RemoteController needs to change the // metadata (e.g. user changes the rating of a song more than once during playback) mApplied = false; } } /** * This receives updates when the current session changes. This is * registered to receive the updates on the handler thread so it can call * directly into the appropriate methods. */ private class MediaControllerCallback extends MediaController.Callback { @Override public void onPlaybackStateChanged(PlaybackState state) { onNewPlaybackState(state); } @Override public void onMetadataChanged(MediaMetadata metadata) { onNewMediaMetadata(metadata); } } /** * Listens for changes to the active session stack and replaces the * currently tracked session if it has changed. */ private class TopTransportSessionListener implements MediaSessionManager.OnActiveSessionsChangedListener { @Override public void onActiveSessionsChanged(List<MediaController> controllers) { int size = controllers.size(); for (int i = 0; i < size; i++) { MediaController controller = controllers.get(i); long flags = controller.getFlags(); // We only care about sessions that handle transport controls, // which will be true for apps using RCC if ((flags & MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS) != 0) { updateController(controller); return; } } updateController(null); } } //================================================== // Event handling private final EventHandler mEventHandler; private final static int MSG_CLIENT_CHANGE = 0; private final static int MSG_NEW_PLAYBACK_STATE = 1; private final static int MSG_NEW_MEDIA_METADATA = 2; private class EventHandler extends Handler { public EventHandler(RemoteController rc, Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { switch(msg.what) { case MSG_CLIENT_CHANGE: onClientChange(msg.arg2 == 1); break; case MSG_NEW_PLAYBACK_STATE: onNewPlaybackState((PlaybackState) msg.obj); break; case MSG_NEW_MEDIA_METADATA: onNewMediaMetadata((MediaMetadata) msg.obj); break; default: Log.e(TAG, "unknown event " + msg.what); } } } /** * @hide */ void startListeningToSessions() { final ComponentName listenerComponent = new ComponentName(mContext, mOnClientUpdateListener.getClass()); Handler handler = null; if (Looper.myLooper() == null) { handler = new Handler(Looper.getMainLooper()); } mSessionManager.addOnActiveSessionsChangedListener(mSessionListener, listenerComponent, UserHandle.myUserId(), handler); mSessionListener.onActiveSessionsChanged(mSessionManager .getActiveSessions(listenerComponent)); if (DEBUG) { Log.d(TAG, "Registered session listener with component " + listenerComponent + " for user " + UserHandle.myUserId()); } } /** * @hide */ void stopListeningToSessions() { mSessionManager.removeOnActiveSessionsChangedListener(mSessionListener); if (DEBUG) { Log.d(TAG, "Unregistered session listener for user " + UserHandle.myUserId()); } } /** If the msg is already queued, replace it with this one. */ private static final int SENDMSG_REPLACE = 0; /** If the msg is already queued, ignore this one and leave the old. */ private static final int SENDMSG_NOOP = 1; /** If the msg is already queued, queue this one and leave the old. */ private static final int SENDMSG_QUEUE = 2; private static void sendMsg(Handler handler, int msg, int existingMsgPolicy, int arg1, int arg2, Object obj, int delayMs) { if (handler == null) { Log.e(TAG, "null event handler, will not deliver message " + msg); return; } if (existingMsgPolicy == SENDMSG_REPLACE) { handler.removeMessages(msg); } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { return; } handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delayMs); } private void onClientChange(boolean clearing) { final OnClientUpdateListener l; synchronized(mInfoLock) { l = mOnClientUpdateListener; mMetadataEditor = null; } if (l != null) { l.onClientChange(clearing); } } private void updateController(MediaController controller) { if (DEBUG) { Log.d(TAG, "Updating controller to " + controller + " previous controller is " + mCurrentSession); } synchronized (mInfoLock) { if (controller == null) { if (mCurrentSession != null) { mCurrentSession.unregisterCallback(mSessionCb); mCurrentSession = null; sendMsg(mEventHandler, MSG_CLIENT_CHANGE, SENDMSG_REPLACE, 0 /* arg1 ignored */, 1 /* clearing */, null /* obj */, 0 /* delay */); } } else if (mCurrentSession == null || !controller.getSessionToken() .equals(mCurrentSession.getSessionToken())) { if (mCurrentSession != null) { mCurrentSession.unregisterCallback(mSessionCb); } sendMsg(mEventHandler, MSG_CLIENT_CHANGE, SENDMSG_REPLACE, 0 /* arg1 ignored */, 0 /* clearing */, null /* obj */, 0 /* delay */); mCurrentSession = controller; mCurrentSession.registerCallback(mSessionCb, mEventHandler); PlaybackState state = controller.getPlaybackState(); sendMsg(mEventHandler, MSG_NEW_PLAYBACK_STATE, SENDMSG_REPLACE, 0 /* arg1 ignored */, 0 /* arg2 ignored */, state /* obj */, 0 /* delay */); MediaMetadata metadata = controller.getMetadata(); sendMsg(mEventHandler, MSG_NEW_MEDIA_METADATA, SENDMSG_REPLACE, 0 /* arg1 ignored */, 0 /* arg2 ignored*/, metadata /* obj */, 0 /*delay*/); } // else same controller, no need to update } } private void onNewPlaybackState(PlaybackState state) { final OnClientUpdateListener l; synchronized (mInfoLock) { l = this.mOnClientUpdateListener; } if (l != null) { int playstate = state == null ? RemoteControlClient.PLAYSTATE_NONE : RemoteControlClient.getRccStateFromState(state.getState()); if (state == null || state.getPosition() == PlaybackState.PLAYBACK_POSITION_UNKNOWN) { l.onClientPlaybackStateUpdate(playstate); } else { l.onClientPlaybackStateUpdate(playstate, state.getLastPositionUpdateTime(), state.getPosition(), state.getPlaybackSpeed()); } if (state != null) { l.onClientTransportControlUpdate( RemoteControlClient.getRccControlFlagsFromActions(state.getActions())); } } } private void onNewMediaMetadata(MediaMetadata metadata) { if (metadata == null) { // RemoteController only handles non-null metadata return; } final OnClientUpdateListener l; final MetadataEditor metadataEditor; // prepare the received Bundle to be used inside a MetadataEditor synchronized(mInfoLock) { l = mOnClientUpdateListener; boolean canRate = mCurrentSession != null && mCurrentSession.getRatingType() != Rating.RATING_NONE; long editableKeys = canRate ? MediaMetadataEditor.RATING_KEY_BY_USER : 0; Bundle legacyMetadata = MediaSessionLegacyHelper.getOldMetadata(metadata, mArtworkWidth, mArtworkHeight); mMetadataEditor = new MetadataEditor(legacyMetadata, editableKeys); metadataEditor = mMetadataEditor; } if (l != null) { l.onClientMetadataUpdate(metadataEditor); } } //================================================== private static class PlaybackInfo { int mState; long mStateChangeTimeMs; long mCurrentPosMs; float mSpeed; PlaybackInfo(int state, long stateChangeTimeMs, long currentPosMs, float speed) { mState = state; mStateChangeTimeMs = stateChangeTimeMs; mCurrentPosMs = currentPosMs; mSpeed = speed; } } /** * @hide * Used by AudioManager to access user listener receiving the client update notifications * @return */ @UnsupportedAppUsage OnClientUpdateListener getUpdateListener() { return mOnClientUpdateListener; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Stack; import com.google.common.base.Preconditions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSExceptionMessages; import org.apache.hadoop.fs.ParentNotDirectoryException; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.AclEntryType; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.protocol.UnresolvedPathException; import org.apache.hadoop.hdfs.server.namenode.INodeAttributeProvider.AccessControlEnforcer; import org.apache.hadoop.hdfs.util.ReadOnlyList; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; /** * Class that helps in checking file system permission. * The state of this class need not be synchronized as it has data structures that * are read-only. * * Some of the helper methods are guarded by {@link FSNamesystem#readLock()}. */ public class FSPermissionChecker implements AccessControlEnforcer { static final Log LOG = LogFactory.getLog(UserGroupInformation.class); private static String getPath(byte[][] components, int start, int end) { return DFSUtil.byteArray2PathString(components, start, end - start + 1); } /** @return a string for throwing {@link AccessControlException} */ private String toAccessControlString(INodeAttributes inodeAttrib, String path, FsAction access) { return toAccessControlString(inodeAttrib, path, access, false); } /** @return a string for throwing {@link AccessControlException} */ private String toAccessControlString(INodeAttributes inodeAttrib, String path, FsAction access, boolean deniedFromAcl) { StringBuilder sb = new StringBuilder("Permission denied: ") .append("user=").append(getUser()).append(", ") .append("access=").append(access).append(", ") .append("inode=\"").append(path).append("\":") .append(inodeAttrib.getUserName()).append(':') .append(inodeAttrib.getGroupName()).append(':') .append(inodeAttrib.isDirectory() ? 'd' : '-') .append(inodeAttrib.getFsPermission()); if (deniedFromAcl) { sb.append("+"); } return sb.toString(); } private final String fsOwner; private final String supergroup; private final UserGroupInformation callerUgi; private final String user; private final Collection<String> groups; private final boolean isSuper; private final INodeAttributeProvider attributeProvider; protected FSPermissionChecker(String fsOwner, String supergroup, UserGroupInformation callerUgi, INodeAttributeProvider attributeProvider) { this.fsOwner = fsOwner; this.supergroup = supergroup; this.callerUgi = callerUgi; this.groups = callerUgi.getGroups(); user = callerUgi.getShortUserName(); isSuper = user.equals(fsOwner) || groups.contains(supergroup); this.attributeProvider = attributeProvider; } public boolean isMemberOfGroup(String group) { return groups.contains(group); } public String getUser() { return user; } public boolean isSuperUser() { return isSuper; } public INodeAttributeProvider getAttributesProvider() { return attributeProvider; } private AccessControlEnforcer getAccessControlEnforcer() { return (attributeProvider != null) ? attributeProvider.getExternalAccessControlEnforcer(this) : this; } /** * Verify if the caller has the required permission. This will result into * an exception if the caller is not allowed to access the resource. */ public void checkSuperuserPrivilege() throws AccessControlException { if (!isSuperUser()) { throw new AccessControlException("Access denied for user " + getUser() + ". Superuser privilege is required"); } } /** * Check whether current user have permissions to access the path. * Traverse is always checked. * * Parent path means the parent directory for the path. * Ancestor path means the last (the closest) existing ancestor directory * of the path. * Note that if the parent path exists, * then the parent path and the ancestor path are the same. * * For example, suppose the path is "/foo/bar/baz". * No matter baz is a file or a directory, * the parent path is "/foo/bar". * If bar exists, then the ancestor path is also "/foo/bar". * If bar does not exist and foo exists, * then the ancestor path is "/foo". * Further, if both foo and bar do not exist, * then the ancestor path is "/". * * @param doCheckOwner Require user to be the owner of the path? * @param ancestorAccess The access required by the ancestor of the path. * @param parentAccess The access required by the parent of the path. * @param access The access required by the path. * @param subAccess If path is a directory, * it is the access required of the path and all the sub-directories. * If path is not a directory, there is no effect. * @param ignoreEmptyDir Ignore permission checking for empty directory? * @throws AccessControlException * * Guarded by {@link FSNamesystem#readLock()} * Caller of this method must hold that lock. */ void checkPermission(INodesInPath inodesInPath, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException { if (LOG.isDebugEnabled()) { LOG.debug("ACCESS CHECK: " + this + ", doCheckOwner=" + doCheckOwner + ", ancestorAccess=" + ancestorAccess + ", parentAccess=" + parentAccess + ", access=" + access + ", subAccess=" + subAccess + ", ignoreEmptyDir=" + ignoreEmptyDir); } // check if (parentAccess != null) && file exists, then check sb // If resolveLink, the check is performed on the link target. final int snapshotId = inodesInPath.getPathSnapshotId(); final INode[] inodes = inodesInPath.getINodesArray(); final INodeAttributes[] inodeAttrs = new INodeAttributes[inodes.length]; final byte[][] components = inodesInPath.getPathComponents(); for (int i = 0; i < inodes.length && inodes[i] != null; i++) { inodeAttrs[i] = getINodeAttrs(components, i, inodes[i], snapshotId); } String path = inodesInPath.getPath(); int ancestorIndex = inodes.length - 2; AccessControlEnforcer enforcer = getAccessControlEnforcer(); enforcer.checkPermission(fsOwner, supergroup, callerUgi, inodeAttrs, inodes, components, snapshotId, path, ancestorIndex, doCheckOwner, ancestorAccess, parentAccess, access, subAccess, ignoreEmptyDir); } /** * Check permission only for the given inode (not checking the children's * access). * * @param inode the inode to check. * @param snapshotId the snapshot id. * @param access the target access. * @throws AccessControlException */ void checkPermission(INode inode, int snapshotId, FsAction access) throws AccessControlException { try { byte[][] localComponents = {inode.getLocalNameBytes()}; INodeAttributes[] iNodeAttr = {inode.getSnapshotINode(snapshotId)}; AccessControlEnforcer enforcer = getAccessControlEnforcer(); enforcer.checkPermission( fsOwner, supergroup, callerUgi, iNodeAttr, // single inode attr in the array new INode[]{inode}, // single inode in the array localComponents, snapshotId, null, -1, // this will skip checkTraverse() because // not checking ancestor here false, null, null, access, // the target access to be checked against the inode null, // passing null sub access avoids checking children false); } catch (AccessControlException ace) { throw new AccessControlException( toAccessControlString(inode, inode.getFullPathName(), access)); } } @Override public void checkPermission(String fsOwner, String supergroup, UserGroupInformation callerUgi, INodeAttributes[] inodeAttrs, INode[] inodes, byte[][] components, int snapshotId, String path, int ancestorIndex, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException { for(; ancestorIndex >= 0 && inodes[ancestorIndex] == null; ancestorIndex--); try { checkTraverse(inodeAttrs, inodes, components, ancestorIndex); } catch (UnresolvedPathException | ParentNotDirectoryException ex) { // must tunnel these exceptions out to avoid breaking interface for // external enforcer throw new TraverseAccessControlException(ex); } final INodeAttributes last = inodeAttrs[inodeAttrs.length - 1]; if (parentAccess != null && parentAccess.implies(FsAction.WRITE) && inodeAttrs.length > 1 && last != null) { checkStickyBit(inodeAttrs, components, inodeAttrs.length - 2); } if (ancestorAccess != null && inodeAttrs.length > 1) { check(inodeAttrs, components, ancestorIndex, ancestorAccess); } if (parentAccess != null && inodeAttrs.length > 1) { check(inodeAttrs, components, inodeAttrs.length - 2, parentAccess); } if (access != null) { check(inodeAttrs, components, inodeAttrs.length - 1, access); } if (subAccess != null) { INode rawLast = inodes[inodeAttrs.length - 1]; checkSubAccess(components, inodeAttrs.length - 1, rawLast, snapshotId, subAccess, ignoreEmptyDir); } if (doCheckOwner) { checkOwner(inodeAttrs, components, inodeAttrs.length - 1); } } private INodeAttributes getINodeAttrs(byte[][] pathByNameArr, int pathIdx, INode inode, int snapshotId) { INodeAttributes inodeAttrs = inode.getSnapshotINode(snapshotId); if (getAttributesProvider() != null) { String[] elements = new String[pathIdx + 1]; /** * {@link INode#getPathComponents(String)} returns a null component * for the root only path "/". Assign an empty string if so. */ if (pathByNameArr.length == 1 && pathByNameArr[0] == null) { elements[0] = ""; } else { for (int i = 0; i < elements.length; i++) { elements[i] = DFSUtil.bytes2String(pathByNameArr[i]); } } inodeAttrs = getAttributesProvider().getAttributes(elements, inodeAttrs); } return inodeAttrs; } /** Guarded by {@link FSNamesystem#readLock()} */ private void checkOwner(INodeAttributes[] inodes, byte[][] components, int i) throws AccessControlException { if (getUser().equals(inodes[i].getUserName())) { return; } throw new AccessControlException( "Permission denied. user=" + getUser() + " is not the owner of inode=" + getPath(components, 0, i)); } /** Guarded by {@link FSNamesystem#readLock()} * @throws AccessControlException * @throws ParentNotDirectoryException * @throws UnresolvedPathException */ private void checkTraverse(INodeAttributes[] inodeAttrs, INode[] inodes, byte[][] components, int last) throws AccessControlException, UnresolvedPathException, ParentNotDirectoryException { for (int i=0; i <= last; i++) { checkIsDirectory(inodes[i], components, i); check(inodeAttrs, components, i, FsAction.EXECUTE); } } /** Guarded by {@link FSNamesystem#readLock()} */ private void checkSubAccess(byte[][] components, int pathIdx, INode inode, int snapshotId, FsAction access, boolean ignoreEmptyDir) throws AccessControlException { if (inode == null || !inode.isDirectory()) { return; } // Each inode in the subtree has a level. The root inode has level 0. // List subINodePath tracks the inode path in the subtree during // traversal. The root inode is not stored because it is already in array // components. The list index is (level - 1). ArrayList<INodeDirectory> subINodePath = new ArrayList<>(); // The stack of levels matches the stack of directory inodes. Stack<Integer> levels = new Stack<>(); levels.push(0); // Level 0 is the root Stack<INodeDirectory> directories = new Stack<INodeDirectory>(); for(directories.push(inode.asDirectory()); !directories.isEmpty(); ) { INodeDirectory d = directories.pop(); int level = levels.pop(); ReadOnlyList<INode> cList = d.getChildrenList(snapshotId); if (!(cList.isEmpty() && ignoreEmptyDir)) { //TODO have to figure this out with inodeattribute provider INodeAttributes inodeAttr = getINodeAttrs(components, pathIdx, d, snapshotId); if (!hasPermission(inodeAttr, access)) { throw new AccessControlException( toAccessControlString(inodeAttr, d.getFullPathName(), access)); } if (level > 0) { if (level - 1 < subINodePath.size()) { subINodePath.set(level - 1, d); } else { Preconditions.checkState(level - 1 == subINodePath.size()); subINodePath.add(d); } } if (inodeAttr.getFsPermission().getStickyBit()) { for (INode child : cList) { INodeAttributes childInodeAttr = getINodeAttrs(components, pathIdx, child, snapshotId); if (isStickyBitViolated(inodeAttr, childInodeAttr)) { List<byte[]> allComponentList = new ArrayList<>(); for (int i = 0; i <= pathIdx; ++i) { allComponentList.add(components[i]); } for (int i = 0; i < level; ++i) { allComponentList.add(subINodePath.get(i).getLocalNameBytes()); } allComponentList.add(child.getLocalNameBytes()); int index = pathIdx + level; byte[][] allComponents = allComponentList.toArray(new byte[][]{}); throwStickyBitException( getPath(allComponents, 0, index + 1), child, getPath(allComponents, 0, index), inode); } } } } for(INode child : cList) { if (child.isDirectory()) { directories.push(child.asDirectory()); levels.push(level + 1); } } } } /** Guarded by {@link FSNamesystem#readLock()} */ private void check(INodeAttributes[] inodes, byte[][] components, int i, FsAction access) throws AccessControlException { INodeAttributes inode = (i >= 0) ? inodes[i] : null; if (inode != null && !hasPermission(inode, access)) { throw new AccessControlException( toAccessControlString(inode, getPath(components, 0, i), access)); } } // return whether access is permitted. note it neither requires a path or // throws so the caller can build the path only if required for an exception. // very beneficial for subaccess checks! private boolean hasPermission(INodeAttributes inode, FsAction access) { if (inode == null) { return true; } final FsPermission mode = inode.getFsPermission(); final AclFeature aclFeature = inode.getAclFeature(); if (aclFeature != null && aclFeature.getEntriesSize() > 0) { // It's possible that the inode has a default ACL but no access ACL. int firstEntry = aclFeature.getEntryAt(0); if (AclEntryStatusFormat.getScope(firstEntry) == AclEntryScope.ACCESS) { return hasAclPermission(inode, access, mode, aclFeature); } } final FsAction checkAction; if (getUser().equals(inode.getUserName())) { //user class checkAction = mode.getUserAction(); } else if (isMemberOfGroup(inode.getGroupName())) { //group class checkAction = mode.getGroupAction(); } else { //other class checkAction = mode.getOtherAction(); } return checkAction.implies(access); } /** * Checks requested access against an Access Control List. This method relies * on finding the ACL data in the relevant portions of {@link FsPermission} and * {@link AclFeature} as implemented in the logic of {@link AclStorage}. This * method also relies on receiving the ACL entries in sorted order. This is * assumed to be true, because the ACL modification methods in * {@link AclTransformation} sort the resulting entries. * * More specifically, this method depends on these invariants in an ACL: * - The list must be sorted. * - Each entry in the list must be unique by scope + type + name. * - There is exactly one each of the unnamed user/group/other entries. * - The mask entry must not have a name. * - The other entry must not have a name. * - Default entries may be present, but they are ignored during enforcement. * * @param inode INodeAttributes accessed inode * @param snapshotId int snapshot ID * @param access FsAction requested permission * @param mode FsPermission mode from inode * @param aclFeature AclFeature of inode * @throws AccessControlException if the ACL denies permission */ private boolean hasAclPermission(INodeAttributes inode, FsAction access, FsPermission mode, AclFeature aclFeature) { boolean foundMatch = false; // Use owner entry from permission bits if user is owner. if (getUser().equals(inode.getUserName())) { if (mode.getUserAction().implies(access)) { return true; } foundMatch = true; } // Check named user and group entries if user was not denied by owner entry. if (!foundMatch) { for (int pos = 0, entry; pos < aclFeature.getEntriesSize(); pos++) { entry = aclFeature.getEntryAt(pos); if (AclEntryStatusFormat.getScope(entry) == AclEntryScope.DEFAULT) { break; } AclEntryType type = AclEntryStatusFormat.getType(entry); String name = AclEntryStatusFormat.getName(entry); if (type == AclEntryType.USER) { // Use named user entry with mask from permission bits applied if user // matches name. if (getUser().equals(name)) { FsAction masked = AclEntryStatusFormat.getPermission(entry).and( mode.getGroupAction()); if (masked.implies(access)) { return true; } foundMatch = true; break; } } else if (type == AclEntryType.GROUP) { // Use group entry (unnamed or named) with mask from permission bits // applied if user is a member and entry grants access. If user is a // member of multiple groups that have entries that grant access, then // it doesn't matter which is chosen, so exit early after first match. String group = name == null ? inode.getGroupName() : name; if (isMemberOfGroup(group)) { FsAction masked = AclEntryStatusFormat.getPermission(entry).and( mode.getGroupAction()); if (masked.implies(access)) { return true; } foundMatch = true; } } } } // Use other entry if user was not denied by an earlier match. return !foundMatch && mode.getOtherAction().implies(access); } /** Guarded by {@link FSNamesystem#readLock()} */ private void checkStickyBit(INodeAttributes[] inodes, byte[][] components, int index) throws AccessControlException { INodeAttributes parent = inodes[index]; if (!parent.getFsPermission().getStickyBit()) { return; } INodeAttributes inode = inodes[index + 1]; if (!isStickyBitViolated(parent, inode)) { return; } throwStickyBitException(getPath(components, 0, index + 1), inode, getPath(components, 0, index), parent); } /** Return true when sticky bit is violated. */ private boolean isStickyBitViolated(INodeAttributes parent, INodeAttributes inode) { // If this user is the directory owner, return if (parent.getUserName().equals(getUser())) { return false; } // if this user is the file owner, return if (inode.getUserName().equals(getUser())) { return false; } return true; } private void throwStickyBitException( String inodePath, INodeAttributes inode, String parentPath, INodeAttributes parent) throws AccessControlException { throw new AccessControlException(String.format( FSExceptionMessages.PERMISSION_DENIED_BY_STICKY_BIT + ": user=%s, path=\"%s\":%s:%s:%s%s, " + "parent=\"%s\":%s:%s:%s%s", user, inodePath, inode.getUserName(), inode.getGroupName(), inode.isDirectory() ? "d" : "-", inode.getFsPermission().toString(), parentPath, parent.getUserName(), parent.getGroupName(), parent.isDirectory() ? "d" : "-", parent.getFsPermission().toString())); } /** * Whether a cache pool can be accessed by the current context * * @param pool CachePool being accessed * @param access type of action being performed on the cache pool * @throws AccessControlException if pool cannot be accessed */ public void checkPermission(CachePool pool, FsAction access) throws AccessControlException { FsPermission mode = pool.getMode(); if (isSuperUser()) { return; } if (getUser().equals(pool.getOwnerName()) && mode.getUserAction().implies(access)) { return; } if (isMemberOfGroup(pool.getGroupName()) && mode.getGroupAction().implies(access)) { return; } if (!getUser().equals(pool.getOwnerName()) && !isMemberOfGroup(pool.getGroupName()) && mode.getOtherAction().implies(access)) { return; } throw new AccessControlException("Permission denied while accessing pool " + pool.getPoolName() + ": user " + getUser() + " does not have " + access.toString() + " permissions."); } /** * Verifies that all existing ancestors are directories. If a permission * checker is provided then the user must have exec access. Ancestor * symlinks will throw an unresolved exception, and resolveLink determines * if the last inode will throw an unresolved exception. This method * should always be called after a path is resolved into an IIP. * @param pc for permission checker, null for no checking * @param iip path to verify * @param resolveLink whether last inode may be a symlink * @throws AccessControlException * @throws UnresolvedPathException * @throws ParentNotDirectoryException */ static void checkTraverse(FSPermissionChecker pc, INodesInPath iip, boolean resolveLink) throws AccessControlException, UnresolvedPathException, ParentNotDirectoryException { try { if (pc == null || pc.isSuperUser()) { checkSimpleTraverse(iip); } else { pc.checkPermission(iip, false, null, null, null, null, false); } } catch (TraverseAccessControlException tace) { // unwrap the non-ACE (unresolved, parent not dir) exception // tunneled out of checker. tace.throwCause(); } // maybe check that the last inode is a symlink if (resolveLink) { int last = iip.length() - 1; checkNotSymlink(iip.getINode(last), iip.getPathComponents(), last); } } // rudimentary permission-less directory check private static void checkSimpleTraverse(INodesInPath iip) throws UnresolvedPathException, ParentNotDirectoryException { byte[][] components = iip.getPathComponents(); for (int i=0; i < iip.length() - 1; i++) { INode inode = iip.getINode(i); if (inode == null) { break; } checkIsDirectory(inode, components, i); } } private static void checkIsDirectory(INode inode, byte[][] components, int i) throws UnresolvedPathException, ParentNotDirectoryException { if (inode != null && !inode.isDirectory()) { checkNotSymlink(inode, components, i); throw new ParentNotDirectoryException( getPath(components, 0, i) + " (is not a directory)"); } } private static void checkNotSymlink(INode inode, byte[][] components, int i) throws UnresolvedPathException { if (inode != null && inode.isSymlink()) { final int last = components.length - 1; final String path = getPath(components, 0, last); final String preceding = getPath(components, 0, i - 1); final String remainder = getPath(components, i + 1, last); final String target = inode.asSymlink().getSymlinkString(); if (LOG.isDebugEnabled()) { final String link = inode.getLocalName(); LOG.debug("UnresolvedPathException " + " path: " + path + " preceding: " + preceding + " count: " + i + " link: " + link + " target: " + target + " remainder: " + remainder); } throw new UnresolvedPathException(path, preceding, remainder, target); } } //used to tunnel non-ACE exceptions encountered during path traversal. //ops that create inodes are expected to throw ParentNotDirectoryExceptions. //the signature of other methods requires the PNDE to be thrown as an ACE. @SuppressWarnings("serial") static class TraverseAccessControlException extends AccessControlException { TraverseAccessControlException(IOException ioe) { super(ioe); } public void throwCause() throws UnresolvedPathException, ParentNotDirectoryException, AccessControlException { Throwable ioe = getCause(); if (ioe instanceof UnresolvedPathException) { throw (UnresolvedPathException)ioe; } if (ioe instanceof ParentNotDirectoryException) { throw (ParentNotDirectoryException)ioe; } throw this; } } }
package com.targomo.client.api.json; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.targomo.client.api.geo.DefaultTargetCoordinate; import java.io.IOException; import java.util.Map; /** * Created by gerb on 01/03/2017. */ public class DefaultTargetCoordinateMapSerializer extends JsonSerializer { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartArray(); // [ for ( Map.Entry<String, DefaultTargetCoordinate> entry : ((Map<String, DefaultTargetCoordinate>) o).entrySet()) { jsonGenerator.writeStartObject(); // { jsonGenerator.writeStringField("id", entry.getKey()); jsonGenerator.writeNumberField("y", entry.getValue().getY()); jsonGenerator.writeNumberField("x", entry.getValue().getX()); jsonGenerator.writeEndObject(); // } } jsonGenerator.writeEndArray(); // ] } }
package org.hbird.transport.protocols.hardware; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.io.InputStream; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class SerialPortDriverTest { // private SerialPortDriver driver; @Before public void setUp() throws Exception { // driver = new SerialPortDriver("/dev/ttyUSB0"); } @Test @Ignore public void testSerialPortDriver() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException { // fail("Not yet implemented"); // FIXME How to test without a serial port library? How could we mock it? // MOckito! - Mark SerialPortDriver driver = new SerialPortDriver("COM5"); driver.getSerialPort().setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); InputStream inStream = driver.getInputStream(); int b = 0; while (true) { b = inStream.read(); } } }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kie.kogito.quarkus.runtime.graal.graal; import java.io.Serializable; import java.util.Map; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.impl.asm.ASMAccessorOptimizer; final class MvelSubstitutions { } @TargetClass(MVEL.class) final class MVEL_Target { @Substitute public static Class analyze(char[] expression, ParserContext ctx) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } @Substitute public static Class analyze(String expression, ParserContext ctx) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } @Substitute public static Serializable compileExpression(String expression, ParserContext ctx) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } @Substitute public static Object executeExpression(final Object compiledExpression, final Object ctx) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } @Substitute public static Object eval(String expression, Map<String, Object> vars) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } @Substitute public static Object eval(String expression) { throw new UnsupportedOperationException("Cannot run MVEL#analyze in native mode"); } } @TargetClass(ASMAccessorOptimizer.class) final class ASMAccessorOptimizer_Target { @Substitute public Accessor optimizeAccessor( ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Class ingressType) { throw new UnsupportedOperationException(); } @Substitute public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType) { throw new UnsupportedOperationException(); } @Substitute public Accessor optimizeCollection(ParserContext pCtx, Object collectionGraph, Class type, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory){ throw new UnsupportedOperationException(); } @Substitute public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory) { throw new UnsupportedOperationException(); } }
/* * Project: WaViewer3D * Version: 1.0 * File: Face.java * *A face which is only adopted for triangles. * * Copyright(C) 2006-2013 Takao WADA. All rights reserved. */ package com.drjiro.viewer; /** * A face which is only adopted for triangles. * * @author wada */ public class Face { /** Vertices */ public Vertex[] vertices; /** Depth */ public float depth; /** * Constructor by 3 vertices. * * @param v1 a vertex * @param v2 a vertex * @param v3 a vertex */ public Face(Vertex v1, Vertex v2, Vertex v3) { vertices = new Vertex[3]; vertices[0] = v1; vertices[1] = v2; vertices[2] = v3; } /** * Retrieve the mean depth for Z-sorting. * * @return depth */ public float getDepth() { return (vertices[0].v.z + vertices[1].v.z + vertices[2].v.z) / 3; } /** * Dump contents. * * @see java.lang.Object#toString() */ public String toString() { return "(" + vertices[0] + "," + vertices[1] + "," + vertices[2] + ")"; } }
/** OutputFile.java * * Copyright May 2018 Tideworks Technology * Author: Roger D. Voss * MIT License */ package com.tideworks.data_load.io; import org.apache.parquet.io.PositionOutputStream; import javax.annotation.Nonnull; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; public final class OutputFile { private static final int IO_BUF_SIZE = 16 * 1024; public static org.apache.parquet.io.OutputFile nioPathToOutputFile(@Nonnull Path file) { //noinspection ConstantConditions assert file != null; return new org.apache.parquet.io.OutputFile() { @Override public PositionOutputStream create(long blockSizeHint) throws IOException { return makePositionOutputStream(file, IO_BUF_SIZE, false); } @Override public PositionOutputStream createOrOverwrite(long blockSizeHint) throws IOException { return makePositionOutputStream(file, IO_BUF_SIZE, true); } @Override public boolean supportsBlockSize() { return false; } @Override public long defaultBlockSize() { return 0; } }; } private static PositionOutputStream makePositionOutputStream(@Nonnull Path file, int ioBufSize, boolean trunc) throws IOException { final OutputStream output = new BufferedOutputStream( Files.newOutputStream(file, CREATE, trunc ? TRUNCATE_EXISTING : APPEND), ioBufSize); return new PositionOutputStream() { private long position = 0; @Override public void write(int b) throws IOException { output.write(b); position++; } @Override public void write(@Nonnull byte[] b) throws IOException { output.write(b); position += b.length; } @Override public void write(@Nonnull byte[] b, int off, int len) throws IOException { output.write(b, off, len); position += len; } @Override public void flush() throws IOException { output.flush(); } @Override public void close() throws IOException { output.close(); } @Override public long getPos() throws IOException { return position; } }; } }
/* * SPDX-License-Identifier: Apache-2.0 * Copyright 2018-2020 The Feast Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package feast.storage.connectors.bigquery.retriever; import static feast.storage.connectors.bigquery.retriever.QueryTemplater.createEntityTableUUIDQuery; import static feast.storage.connectors.bigquery.retriever.QueryTemplater.createTimestampLimitQuery; import com.google.auto.value.AutoValue; import com.google.cloud.RetryOption; import com.google.cloud.bigquery.*; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import feast.proto.core.FeatureSetProto.FeatureSpec; import feast.proto.serving.ServingAPIProto; import feast.proto.serving.ServingAPIProto.DataFormat; import feast.proto.serving.ServingAPIProto.DatasetSource; import feast.proto.serving.ServingAPIProto.FeatureReference; import feast.storage.api.retriever.FeatureSetRequest; import feast.storage.api.retriever.HistoricalRetrievalResult; import feast.storage.api.retriever.HistoricalRetriever; import feast.storage.api.statistics.FeatureStatistics; import feast.storage.connectors.bigquery.statistics.BigQueryStatisticsRetriever; import feast.storage.connectors.bigquery.statistics.FeatureStatisticsQueryInfo; import feast.storage.connectors.bigquery.statistics.StatsDataset; import io.grpc.Status; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.*; import java.util.stream.Collectors; import org.slf4j.Logger; import org.tensorflow.metadata.v0.DatasetFeatureStatistics; import org.tensorflow.metadata.v0.DatasetFeatureStatisticsList; import org.threeten.bp.Duration; @AutoValue public abstract class BigQueryHistoricalRetriever implements HistoricalRetriever { private static final Logger log = org.slf4j.LoggerFactory.getLogger(BigQueryHistoricalRetriever.class); public static final long TEMP_TABLE_EXPIRY_DURATION_MS = Duration.ofDays(1).toMillis(); private static final long SUBQUERY_TIMEOUT_SECS = 900; // 15 minutes public static HistoricalRetriever create(Map<String, String> config) { BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); Storage storage = StorageOptions.getDefaultInstance().getService(); String jobStagingLocation = config.get("staging_location"); if (!jobStagingLocation.contains("://")) { throw new IllegalArgumentException( String.format("jobStagingLocation is not a valid URI: %s", jobStagingLocation)); } if (jobStagingLocation.endsWith("/")) { jobStagingLocation = jobStagingLocation.substring(0, jobStagingLocation.length() - 1); } if (!jobStagingLocation.startsWith("gs://")) { throw new IllegalArgumentException( "Store type BIGQUERY requires job staging location to be a valid and existing Google Cloud Storage URI. Invalid staging location: " + jobStagingLocation); } return builder() .setBigquery(bigquery) .setDatasetId(config.get("dataset_id")) .setProjectId(config.get("project_id")) .setJobStagingLocation(config.get("staging_location")) .setInitialRetryDelaySecs(Integer.parseInt(config.get("initial_retry_delay_seconds"))) .setTotalTimeoutSecs(Integer.parseInt(config.get("total_timeout_seconds"))) .setStorage(storage) .build(); } public abstract String projectId(); public abstract String datasetId(); public abstract BigQuery bigquery(); public abstract String jobStagingLocation(); public abstract int initialRetryDelaySecs(); public abstract int totalTimeoutSecs(); public abstract Storage storage(); public static Builder builder() { return new AutoValue_BigQueryHistoricalRetriever.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder setProjectId(String projectId); public abstract Builder setDatasetId(String datasetId); public abstract Builder setJobStagingLocation(String jobStagingLocation); public abstract Builder setBigquery(BigQuery bigquery); public abstract Builder setInitialRetryDelaySecs(int initialRetryDelaySecs); public abstract Builder setTotalTimeoutSecs(int totalTimeoutSecs); public abstract Builder setStorage(Storage storage); public abstract BigQueryHistoricalRetriever build(); } @Override public String getStagingLocation() { return jobStagingLocation(); } @Override public HistoricalRetrievalResult getHistoricalFeatures( String retrievalId, DatasetSource datasetSource, List<FeatureSetRequest> featureSetRequests, boolean computeStatistics) { List<FeatureSetQueryInfo> featureSetQueryInfos = QueryTemplater.getFeatureSetInfos(featureSetRequests); // 1. load entity table Table entityTable; String entityTableName; try { entityTable = loadEntities(datasetSource); TableId entityTableWithUUIDs = generateUUIDs(entityTable); entityTableName = generateFullTableName(entityTableWithUUIDs); } catch (Exception e) { return HistoricalRetrievalResult.error( retrievalId, new RuntimeException( String.format("Unable to load entity table to BigQuery: %s", e.toString()))); } Schema entityTableSchema = entityTable.getDefinition().getSchema(); List<String> entityTableColumnNames = entityTableSchema.getFields().stream() .map(Field::getName) .filter(name -> !name.equals("event_timestamp")) .collect(Collectors.toList()); // 2. Retrieve the temporal bounds of the entity dataset provided FieldValueList timestampLimits = getTimestampLimits(entityTableName); // 3. Generate the subqueries List<String> featureSetQueries = generateQueries(entityTableName, timestampLimits, featureSetQueryInfos); QueryJobConfiguration queryConfig; try { // 4. Run the subqueries in parallel then collect the outputs Job queryJob = runBatchQuery( entityTableName, entityTableColumnNames, featureSetQueryInfos, featureSetQueries); queryConfig = queryJob.getConfiguration(); String exportTableDestinationUri = String.format("%s/%s/*.avro", jobStagingLocation(), retrievalId); // 5. Export the table // Hardcode the format to Avro for now ExtractJobConfiguration extractConfig = ExtractJobConfiguration.of( queryConfig.getDestinationTable(), exportTableDestinationUri, "Avro"); Job extractJob = bigquery().create(JobInfo.of(extractConfig)); waitForJob(extractJob); } catch (BigQueryException | InterruptedException | IOException e) { return HistoricalRetrievalResult.error(retrievalId, e); } List<String> fileUris = parseOutputFileURIs(retrievalId); HistoricalRetrievalResult result = HistoricalRetrievalResult.success(retrievalId, fileUris, DataFormat.DATA_FORMAT_AVRO); // 6. If the user requested to compute statistics, compute them over the output table if (computeStatistics) { BigQueryStatisticsRetriever statsRetriever = BigQueryStatisticsRetriever.newBuilder() .setProjectId(projectId()) .setDatasetId(datasetId()) .setBigquery(bigquery()) .build(); List<FeatureStatisticsQueryInfo> featureStatisticsQueryInfos = buildFeatureStatisticsQuery(featureSetRequests); FeatureStatistics featureStatistics = statsRetriever.getFeatureStatistics( featureStatisticsQueryInfos, new StatsDataset(queryConfig.getDestinationTable())); DatasetFeatureStatisticsList datasetFeatureStatisticsList = DatasetFeatureStatisticsList.newBuilder() .addDatasets( DatasetFeatureStatistics.newBuilder() .addAllFeatures(featureStatistics.getFeatureNameStatistics()) .setNumExamples(featureStatistics.getNumExamples())) .build(); result = result.withStats(datasetFeatureStatisticsList); } return result; } private List<FeatureStatisticsQueryInfo> buildFeatureStatisticsQuery( List<FeatureSetRequest> featureSetRequests) { List<FeatureStatisticsQueryInfo> featureStatisticsQueryInfos = new ArrayList<>(); for (FeatureSetRequest request : featureSetRequests) { Map<String, FeatureReference> refsByName = request.getFeatureRefsByName(); for (FeatureSpec featureSpec : request.getSpec().getFeaturesList()) { FeatureReference ref = refsByName.getOrDefault(featureSpec.getName(), null); if (ref != null) { if (!ref.getFeatureSet().equals("")) { featureSpec = featureSpec .toBuilder() .setName(String.format("%s__%s", ref.getFeatureSet(), ref.getName())) .build(); } featureStatisticsQueryInfos.add(FeatureStatisticsQueryInfo.fromProto(featureSpec)); } } } return featureStatisticsQueryInfos; } private TableId generateUUIDs(Table loadedEntityTable) { try { String uuidQuery = createEntityTableUUIDQuery(generateFullTableName(loadedEntityTable.getTableId())); QueryJobConfiguration queryJobConfig = QueryJobConfiguration.newBuilder(uuidQuery) .setDestinationTable(TableId.of(projectId(), datasetId(), createTempTableName())) .build(); Job queryJob = bigquery().create(JobInfo.of(queryJobConfig)); Job completedJob = waitForJob(queryJob); TableInfo expiry = bigquery() .getTable(queryJobConfig.getDestinationTable()) .toBuilder() .setExpirationTime(System.currentTimeMillis() + TEMP_TABLE_EXPIRY_DURATION_MS) .build(); bigquery().update(expiry); queryJobConfig = completedJob.getConfiguration(); return queryJobConfig.getDestinationTable(); } catch (InterruptedException | BigQueryException e) { throw Status.INTERNAL .withDescription("Failed to load entity dataset into store") .withCause(e) .asRuntimeException(); } } private FieldValueList getTimestampLimits(String entityTableName) { QueryJobConfiguration getTimestampLimitsQuery = QueryJobConfiguration.newBuilder(createTimestampLimitQuery(entityTableName)) .setDefaultDataset(DatasetId.of(projectId(), datasetId())) .setDestinationTable(TableId.of(projectId(), datasetId(), createTempTableName())) .build(); try { Job job = bigquery().create(JobInfo.of(getTimestampLimitsQuery)); TableResult getTimestampLimitsQueryResult = waitForJob(job).getQueryResults(); TableInfo expiry = bigquery() .getTable(getTimestampLimitsQuery.getDestinationTable()) .toBuilder() .setExpirationTime(System.currentTimeMillis() + TEMP_TABLE_EXPIRY_DURATION_MS) .build(); bigquery().update(expiry); FieldValueList result = null; for (FieldValueList fields : getTimestampLimitsQueryResult.getValues()) { result = fields; } if (result == null || result.get("min").isNull() || result.get("max").isNull()) { throw new RuntimeException("query returned insufficient values"); } return result; } catch (InterruptedException e) { throw Status.INTERNAL .withDescription("Unable to extract min and max timestamps from query") .withCause(e) .asRuntimeException(); } } private Table loadEntities(ServingAPIProto.DatasetSource datasetSource) { Table loadedEntityTable; switch (datasetSource.getDatasetSourceCase()) { case FILE_SOURCE: try { // Currently only AVRO format is supported if (datasetSource.getFileSource().getDataFormat() != ServingAPIProto.DataFormat.DATA_FORMAT_AVRO) { throw Status.INVALID_ARGUMENT .withDescription("Invalid file format, only AVRO is supported.") .asRuntimeException(); } TableId tableId = TableId.of(projectId(), datasetId(), createTempTableName()); log.info( "Loading entity rows to: {}.{}.{}", projectId(), datasetId(), tableId.getTable()); LoadJobConfiguration loadJobConfiguration = LoadJobConfiguration.of( tableId, datasetSource.getFileSource().getFileUrisList(), FormatOptions.avro()); loadJobConfiguration = loadJobConfiguration.toBuilder().setUseAvroLogicalTypes(true).build(); Job job = bigquery().create(JobInfo.of(loadJobConfiguration)); waitForJob(job); TableInfo expiry = bigquery() .getTable(tableId) .toBuilder() .setExpirationTime(System.currentTimeMillis() + TEMP_TABLE_EXPIRY_DURATION_MS) .build(); bigquery().update(expiry); loadedEntityTable = bigquery().getTable(tableId); if (!loadedEntityTable.exists()) { throw new RuntimeException( "Unable to create entity dataset table, table already exists"); } return loadedEntityTable; } catch (Exception e) { log.error("Exception has occurred in loadEntities method: ", e); throw Status.INTERNAL .withDescription("Failed to load entity dataset into store: " + e.toString()) .withCause(e) .asRuntimeException(); } case DATASETSOURCE_NOT_SET: default: throw Status.INVALID_ARGUMENT .withDescription("Data source must be set.") .asRuntimeException(); } } private List<String> generateQueries( String entityTableName, FieldValueList timestampLimits, List<FeatureSetQueryInfo> featureSetQueryInfos) { List<String> featureSetQueries = new ArrayList<>(); try { for (FeatureSetQueryInfo featureSetInfo : featureSetQueryInfos) { String query = QueryTemplater.createFeatureSetPointInTimeQuery( featureSetInfo, projectId(), datasetId(), entityTableName, timestampLimits.get("min").getStringValue(), timestampLimits.get("max").getStringValue()); featureSetQueries.add(query); } } catch (IOException e) { throw Status.INTERNAL .withDescription("Unable to generate query for batch retrieval") .withCause(e) .asRuntimeException(); } return featureSetQueries; } Job runBatchQuery( String entityTableName, List<String> entityTableColumnNames, List<FeatureSetQueryInfo> featureSetQueryInfos, List<String> featureSetQueries) throws BigQueryException, InterruptedException, IOException { ExecutorService executorService = Executors.newFixedThreadPool(featureSetQueries.size()); ExecutorCompletionService<FeatureSetQueryInfo> executorCompletionService = new ExecutorCompletionService<>(executorService); // For each of the feature sets requested, start an async job joining the features in that // feature set to the provided entity table for (int i = 0; i < featureSetQueries.size(); i++) { QueryJobConfiguration queryJobConfig = QueryJobConfiguration.newBuilder(featureSetQueries.get(i)) .setDestinationTable(TableId.of(projectId(), datasetId(), createTempTableName())) .build(); Job subqueryJob = bigquery().create(JobInfo.of(queryJobConfig)); executorCompletionService.submit( SubqueryCallable.builder() .setBigquery(bigquery()) .setFeatureSetInfo(featureSetQueryInfos.get(i)) .setSubqueryJob(subqueryJob) .build()); } List<FeatureSetQueryInfo> completedFeatureSetQueryInfos = new ArrayList<>(); for (int i = 0; i < featureSetQueries.size(); i++) { try { // Try to retrieve the outputs of all the jobs. The timeout here is a formality; // a stricter timeout is implemented in the actual SubqueryCallable. FeatureSetQueryInfo featureSetInfo = executorCompletionService.take().get(SUBQUERY_TIMEOUT_SECS, TimeUnit.SECONDS); completedFeatureSetQueryInfos.add(featureSetInfo); } catch (InterruptedException | ExecutionException | TimeoutException e) { executorService.shutdownNow(); throw Status.INTERNAL .withDescription("Error running batch query") .withCause(e) .asRuntimeException(); } } // Generate and run a join query to collect the outputs of all the // subqueries into a single table. String joinQuery = QueryTemplater.createJoinQuery( completedFeatureSetQueryInfos, entityTableColumnNames, entityTableName); QueryJobConfiguration queryJobConfig = QueryJobConfiguration.newBuilder(joinQuery) .setDestinationTable(TableId.of(projectId(), datasetId(), createTempTableName())) .build(); Job queryJob = bigquery().create(JobInfo.of(queryJobConfig)); Job completedQueryJob = waitForJob(queryJob); TableInfo expiry = bigquery() .getTable(queryJobConfig.getDestinationTable()) .toBuilder() .setExpirationTime(System.currentTimeMillis() + TEMP_TABLE_EXPIRY_DURATION_MS) .build(); bigquery().update(expiry); return completedQueryJob; } private List<String> parseOutputFileURIs(String feastJobId) { String scheme = jobStagingLocation().substring(0, jobStagingLocation().indexOf("://")); String stagingLocationNoScheme = jobStagingLocation().substring(jobStagingLocation().indexOf("://") + 3); String bucket = stagingLocationNoScheme.split("/")[0]; List<String> prefixParts = new ArrayList<>(); prefixParts.add( stagingLocationNoScheme.contains("/") && !stagingLocationNoScheme.endsWith("/") ? stagingLocationNoScheme.substring(stagingLocationNoScheme.indexOf("/") + 1) : ""); prefixParts.add(feastJobId); String prefix = String.join("/", prefixParts) + "/"; List<String> fileUris = new ArrayList<>(); for (Blob blob : storage().list(bucket, Storage.BlobListOption.prefix(prefix)).iterateAll()) { fileUris.add(String.format("%s://%s/%s", scheme, blob.getBucket(), blob.getName())); } return fileUris; } private Job waitForJob(Job queryJob) throws InterruptedException { Job completedJob = queryJob.waitFor( RetryOption.initialRetryDelay(Duration.ofSeconds(initialRetryDelaySecs())), RetryOption.totalTimeout(Duration.ofSeconds(totalTimeoutSecs()))); if (completedJob == null) { throw Status.INTERNAL.withDescription("Job no longer exists").asRuntimeException(); } else if (completedJob.getStatus().getError() != null) { throw Status.INTERNAL .withDescription("Job failed: " + completedJob.getStatus().getError()) .asRuntimeException(); } return completedJob; } public String generateFullTableName(TableId tableId) { return String.format( "%s.%s.%s", tableId.getProject(), tableId.getDataset(), tableId.getTable()); } public String createTempTableName() { return "_" + UUID.randomUUID().toString().replace("-", ""); } }
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.engine.spi; /** * @author Steve Ebersole */ public interface PersistentAttributeInterceptor { public boolean readBoolean(Object obj, String name, boolean oldValue); public boolean writeBoolean(Object obj, String name, boolean oldValue, boolean newValue); public byte readByte(Object obj, String name, byte oldValue); public byte writeByte(Object obj, String name, byte oldValue, byte newValue); public char readChar(Object obj, String name, char oldValue); public char writeChar(Object obj, String name, char oldValue, char newValue); public short readShort(Object obj, String name, short oldValue); public short writeShort(Object obj, String name, short oldValue, short newValue); public int readInt(Object obj, String name, int oldValue); public int writeInt(Object obj, String name, int oldValue, int newValue); public float readFloat(Object obj, String name, float oldValue); public float writeFloat(Object obj, String name, float oldValue, float newValue); public double readDouble(Object obj, String name, double oldValue); public double writeDouble(Object obj, String name, double oldValue, double newValue); public long readLong(Object obj, String name, long oldValue); public long writeLong(Object obj, String name, long oldValue, long newValue); public Object readObject(Object obj, String name, Object oldValue); public Object writeObject(Object obj, String name, Object oldValue, Object newValue); }
package com.gy.service.impl; import com.gy.dao.UserDao; import com.gy.dto.RegisterDto; import com.gy.model.User; import com.gy.service.UserService; import org.jasypt.util.password.PasswordEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Autowired private PasswordEncryptor passwordEncryptor; @Override public User add(RegisterDto registerDto) { User user = new User(); user.setUsername(registerDto.getUsername()); user.setPhone(registerDto.getPhone()); user.setEmail(registerDto.getEmail()); // encryptPassword 加密密码 user.setPwdHash(passwordEncryptor.encryptPassword(registerDto.getPwd())); userDao.add(user); return user; //return userDao.getById(user.getId()); } }
/* * Copyright 2021 gparap * * 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 gparap.apps.countdown_timer; import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import gparap.apps.countdown_timer.utils.Utils; public class MainActivity extends AppCompatActivity { EditText editTextHours, editTextMinutes, editTextSeconds; int hours, minutes, seconds; long millisInFuture; boolean isTimeCorrect; //helper to check the correctness of the time field values CountDownTimer countDownTimer; boolean isCounting; //helper to control the countdown View editTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setupCounter(); } private void init() { //get widgets editTextHours = findViewById(R.id.editTextHours); editTextMinutes = findViewById(R.id.editTextMinutes); editTextSeconds = findViewById(R.id.editTextSeconds); hours = minutes = seconds = 0; millisInFuture = 0L; isTimeCorrect = true; isCounting = false; //set colors when input fields are disabled (because of countdown) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { editTextHours.setTextColor(getResources().getColor(R.color.colorInputDisabled, null)); editTextMinutes.setTextColor(getResources().getColor(R.color.colorInputDisabled, null)); editTextSeconds.setTextColor(getResources().getColor(R.color.colorInputDisabled, null)); } else { editTextHours.setTextColor(getResources().getColor(R.color.colorInputDisabled)); editTextMinutes.setTextColor(getResources().getColor(R.color.colorInputDisabled)); editTextSeconds.setTextColor(getResources().getColor(R.color.colorInputDisabled)); } } public void onClickStart(View view) { startCounter(); } //Sets up the correct time values for the countdown private void setupCounter() { //correct hours field value isTimeCorrect = true; editTextHours.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { //get a reference to the edit text editTextView = getCurrentFocus(); //display hint if no value editTextHours.setHint("0"); try { //fix hours ( <= 23) if (Integer.parseInt(editTextHours.getText().toString()) > 23) { isTimeCorrect = false; } } catch (Exception ignored) { } finally { try { if (!isTimeCorrect) { if (Integer.parseInt(editTextHours.getText().toString()) > 23) { editTextHours.setText(R.string.value_23); } } } catch (Exception ignored) { } } } }); //correct minutes field value isTimeCorrect = true; editTextMinutes.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { //get a reference to the edit text editTextView = getCurrentFocus(); //display hint if no value editTextMinutes.setHint("0"); try { //fix minutes (<= 59) if (Integer.parseInt(editTextMinutes.getText().toString()) > 59) { isTimeCorrect = false; } } catch (Exception ignored) { } finally { try { if (!isTimeCorrect) if (Integer.parseInt(editTextMinutes.getText().toString()) > 59) { editTextMinutes.setText(R.string.value_59); } } catch (Exception ignored) { } } } }); //correct seconds field value isTimeCorrect = true; editTextSeconds.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { //get a reference to the edit text editTextView = getCurrentFocus(); //display hint if no value editTextSeconds.setHint("0"); try { //fix seconds (<= 60) if (Integer.parseInt(editTextSeconds.getText().toString()) > 59) { isTimeCorrect = false; } } catch (Exception ignored) { } finally { try { if (!isTimeCorrect) if (Integer.parseInt(editTextSeconds.getText().toString()) > 59) { editTextSeconds.setText(R.string.value_59); } } catch (Exception ignored) { } } } }); } //Start the countdown private void startCounter() { if (!isCounting) { //get time from the edit fields if (!editTextHours.getText().toString().equals("")) { hours = Integer.parseInt(editTextHours.getText().toString()); editTextHours.setText(String.valueOf(hours)); //remove redundant zeros } if (!editTextMinutes.getText().toString().equals("")) { minutes = Integer.parseInt(editTextMinutes.getText().toString()); editTextMinutes.setText(String.valueOf(minutes)); //remove redundant zeros } if (!editTextSeconds.getText().toString().equals("")) { seconds = Integer.parseInt(editTextSeconds.getText().toString()); editTextSeconds.setText(String.valueOf(seconds)); //remove redundant zeros } //compute the total number of milliseconds in the future until the countdown is done millisInFuture = Utils.getInstance().convertSecondsToMillis(seconds); millisInFuture += Utils.getInstance().convertMinutesToMillis(minutes); millisInFuture += Utils.getInstance().convertHoursToMillis(hours); //start the countdown countDownTimer = new CountDownTimer(millisInFuture, 1000) { @Override public void onTick(long millisUntilFinished) { //display seconds seconds -= 1; editTextSeconds.setText(String.valueOf(seconds)); //display minutes if (seconds < 0) { seconds = 59; editTextSeconds.setText(String.valueOf(seconds)); minutes -= 1; editTextMinutes.setText(String.valueOf(minutes)); } //display hours if (minutes < 0) { minutes = 59; editTextMinutes.setText(String.valueOf(minutes)); hours -= 1; editTextHours.setText(String.valueOf(hours)); } } @Override public void onFinish() { isCounting = false; //register an intent to be broadcast by the receiver Intent intent = new Intent(MainActivity.this, CountdownReceiver.class); @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent .getBroadcast(getApplicationContext(), 0, intent, 0); //create an alarm manager to schedule the broadcast AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent); } }; //check if not all fields are zero if ((!editTextHours.getText().toString().isEmpty() && !editTextHours.getText().toString().equals("0")) || (!editTextMinutes.getText().toString().isEmpty() && !editTextMinutes.getText().toString().equals("0")) || (!editTextSeconds.getText().toString().isEmpty() && !editTextSeconds.getText().toString().equals("0"))) { //start countdown countDownTimer.start(); isCounting = true; //close virtual keyboard if start button is pressed if (editTextView != null) { InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(editTextView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } //disable input fields editTextHours.setEnabled(false); editTextMinutes.setEnabled(false); editTextSeconds.setEnabled(false); } } } //Reset the counter public void OnClickButtonReset(View view) { //stop countdown if (countDownTimer != null) countDownTimer.cancel(); isCounting = false; //clear values hours = minutes = seconds = 0; //clear fields editTextHours.setText(""); editTextMinutes.setText(""); editTextSeconds.setText(""); //show hints editTextHours.setHint("0"); editTextMinutes.setHint("0"); editTextSeconds.setHint("0"); //enable input fields editTextHours.setEnabled(true); editTextMinutes.setEnabled(true); editTextSeconds.setEnabled(true); } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); //save state outState.putInt("hours", hours); outState.putInt("minutes", minutes); outState.putInt("seconds", seconds); outState.putBoolean("isCounting", isCounting); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); //restore state isCounting = savedInstanceState.getBoolean("isCounting"); hours = savedInstanceState.getInt("hours"); minutes = savedInstanceState.getInt("minutes"); seconds = savedInstanceState.getInt("seconds"); //there was an orientation change //and the timer was counting if (isCounting) { //restart the counter isCounting = false; startCounter(); isCounting = true; } } }
package com.manage.framework.config; import java.util.Random; import com.google.code.kaptcha.text.impl.DefaultTextCreator; /** * 验证码文本生成器 * * @author ruoyi */ public class KaptchaTextCreator extends DefaultTextCreator { private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); @Override public String getText() { Integer result = 0; Random random = new Random(); int x = random.nextInt(10); int y = random.nextInt(10); StringBuilder suChinese = new StringBuilder(); int randomoperands = (int) Math.round(Math.random() * 2); if (randomoperands == 0) { result = x * y; suChinese.append(CNUMBERS[x]); suChinese.append("*"); suChinese.append(CNUMBERS[y]); } else if (randomoperands == 1) { if (!(x == 0) && y % x == 0) { result = y / x; suChinese.append(CNUMBERS[y]); suChinese.append("/"); suChinese.append(CNUMBERS[x]); } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } } else if (randomoperands == 2) { if (x >= y) { result = x - y; suChinese.append(CNUMBERS[x]); suChinese.append("-"); suChinese.append(CNUMBERS[y]); } else { result = y - x; suChinese.append(CNUMBERS[y]); suChinese.append("-"); suChinese.append(CNUMBERS[x]); } } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } suChinese.append("=?@" + result); return suChinese.toString(); } }
package externa; // anotações @Informacao( autor = "rodrigo", aulaNumero = 65, blog = "rodrigo.com" ) public class Externa { private String texto = "texto externo"; public class Interna { private String texto = "texto interno"; public void imprimeTexto(){ System.out.println (texto); // acessando a mais externa System.out.println (Externa.this.texto); } } public static void main(String[] args) { Externa externa = new Externa(); Interna interna = externa.new Interna(); interna.imprimeTexto(); } }
package app.weasel.activity; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.gson.Gson; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.concurrent.TimeUnit; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.widget.AppCompatTextView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import app.weasel.R; import app.weasel.event.NewQueueItemEvent; import app.weasel.event.SongDiscoveryEvent; import app.weasel.views.FixedWebView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public final class BrowserActivity extends BaseActivity { private static final String TAG = "BrowserFragment"; @BindView(R.id.webView) FixedWebView mWebView; @BindView(R.id.swipeRefresh) SwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.fab) FloatingActionButton mCancelLoadingFab; @BindView(R.id.statusText) AppCompatTextView mStatusText; @BindView(R.id.statusView) View mStatusView; private final Gson mGson = new Gson(); private Handler mHandler; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acivity_browser); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ButterKnife.bind(this); mSwipeRefreshLayout.setOnRefreshListener(() -> { mCancelLoadingFab.show(); mWebView.reload(); } ); mHandler = new Handler(); setupWebView(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mWebView.saveState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mWebView.restoreState(savedInstanceState); } @Override protected void onResume() { super.onResume(); if (!EventBus.getDefault().isRegistered(this)) { // Because parent is/(might be) already registered EventBus.getDefault().register(this); } } @Override protected void onPause() { super.onPause(); EventBus.getDefault().unregister(this); } @OnClick(R.id.fab) void cancelWebViewLoading() { mWebView.stopLoading(); } private void setupWebView() { final WebSettings webSettings = mWebView.getSettings(); webSettings.setBuiltInZoomControls(false); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); mWebView.setBackgroundColor(Color.TRANSPARENT); mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { mSwipeRefreshLayout.setRefreshing(false); mCancelLoadingFab.hide(); } else { if (!mSwipeRefreshLayout.isRefreshing()) { mCancelLoadingFab.show(); mSwipeRefreshLayout.setRefreshing(true); } } } }); mWebView.setWebViewClient(new WebViewClient() { // We could have used mWebView.addJavascriptInterface(); but that poses security threats // to the app and device @Override public void onPageFinished(WebView view, String url) { Log.v(TAG, "onPageFinished"); String fn = "(" + "function(){" + "var c = document.getElementsByTagName('a');" + "var ids=[];" + "var cb=function(arr,v){ if(v != null && arr.indexOf(v)==-1){arr.push(v); return true;} return false;};" + "for(var i=0; i<c.length; i++){" + "var x=/(song\\=([0-9]+))|(song\\.php\\?id\\=([0-9]+))|([A-Z]\\/[0-9]+-.+\\/[0-9]+-.+\\/([0-9]+)-.+$)/.exec(c[i].href);" + "if(x != null){" + "if(!cb(ids, x[2])) if(!cb(ids, x[4])) cb(ids, x[6]);" + "}" + "}" + "return ids;" + "}" + ")()"; view.evaluateJavascript(fn, result -> { if (result != null) { result = result.replace("\"", ""); final long[] idList = mGson.fromJson(result, long[].class); if (idList.length > 0) { EventBus.getDefault().post(new NewQueueItemEvent(idList)); } Log.v(TAG, "Found " + idList.length + " ids"); } }); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.v(TAG, "onPageStarted"); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (filterResource(url)) { return true; } return super.shouldOverrideUrlLoading(view, url); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (filterResource(request.getUrl().toString())) { return true; } return super.shouldOverrideUrlLoading(view, request); } }); mWebView.loadUrl("http://m.malawi-music.com/"); } @Override public void onBackPressed() { if (mWebView.canGoBack()) { mWebView.goBack(); } else { super.onBackPressed(); } } @Subscribe(threadMode = ThreadMode.MAIN_ORDERED) public void onSongDiscovered(SongDiscoveryEvent event) { switch (event.getEventCode()) { case song_discovered: mHandler.removeCallbacks(mStatusViewDismisser); mStatusView.setVisibility(View.VISIBLE); mStatusText.setText(event.getSongTitle()); mHandler.postDelayed(mStatusViewDismisser, TimeUnit.SECONDS.toMillis(5)); break; } } private final Runnable mStatusViewDismisser = new Runnable() { @Override public void run() { mStatusView.setVisibility(View.GONE); } }; private boolean filterResource(String url) { // TODO block annoying advertisement assets here (EasyList) return false; } }
package net.mfinance.chatlib.utils; import android.util.Log; import java.text.DecimalFormat; public class NumberPriceUtil { /** * 转成以万为单位 * @param num 整数 */ public static String toThou(int num) { // 设置保留位数 DecimalFormat df = new DecimalFormat("0.00"); float pp = (float)num / 10000; String format = df.format(pp); Log.e("num", "format = " + format); String point = removePoint(format); return point; } /** * 去掉小数点后面的0 22.010 -> 22.01 */ public static String removePoint(String num) { if(num.indexOf(".") > 0){ // 去掉后面无用的零 num = num.replaceAll("0+?$", ""); // 如小数点后面全是零则去掉小数点 num = num.replaceAll("[.]$", ""); } return num; } }
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.components.table.fill; import java.io.Serializable; import net.sf.jasperreports.engine.JRConstants; import net.sf.jasperreports.engine.JRPropertiesHolder; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.base.JRBaseObjectFactory; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) * @version $Id: TableJasperReport.java 7199 2014-08-27 13:58:10Z teodord $ */ public class TableJasperReport extends JasperReport { private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; private final JasperReport parentReport; private final TableReport tableReport; public TableJasperReport(JasperReport parentReport, TableReport baseReport, Serializable compileData, JRBaseObjectFactory factory, String compileNameSuffix) { super(baseReport, parentReport.getCompilerClass(), compileData, factory, compileNameSuffix); this.parentReport = parentReport; this.tableReport = baseReport; } public JasperReport getParentReport() { return parentReport; } @Override public JRPropertiesHolder getParentProperties() { // the subreport created for the table inherits all properties from the containing report return parentReport; } public TableReport getBaseReport() { return tableReport; } }
/* * Copyright 2017-2020 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.gaffer.store.serialiser; import org.junit.Before; import org.junit.Test; import uk.gov.gchq.gaffer.commonutil.TestGroups; import uk.gov.gchq.gaffer.data.element.Entity; import uk.gov.gchq.gaffer.exception.SerialisationException; import uk.gov.gchq.gaffer.serialisation.implementation.StringSerialiser; import uk.gov.gchq.gaffer.store.schema.Schema; import uk.gov.gchq.gaffer.store.schema.SchemaEntityDefinition; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class EntitySerialiserTest { private Schema schema; private EntitySerialiser serialiser; @Before public void setUp() { final SchemaEntityDefinition entityDef = new SchemaEntityDefinition.Builder() .build(); schema = new Schema.Builder() .vertexSerialiser(new StringSerialiser()) .entity(TestGroups.ENTITY, entityDef) .build(); serialiser = new EntitySerialiser(schema); } @Test public void testNullSerialiser() { // Given schema = new Schema.Builder().build(); // When / Then try { serialiser = new EntitySerialiser(schema); fail("Exception expected"); } catch (final IllegalArgumentException e) { assertTrue(e.getMessage().contains("Vertex serialiser is required")); } } @Test public void testCanSerialiseEntity() throws SerialisationException { // Given final Entity entity = new Entity(TestGroups.ENTITY, "testVertex"); // When final byte[] serialisedEntity = serialiser.serialise(entity); final Entity deserialisedEntity = serialiser.deserialise(serialisedEntity); // Then assertEquals(entity, deserialisedEntity); } @Test public void testCantSerialiseIntegerClass() throws SerialisationException { assertFalse(serialiser.canHandle(Integer.class)); } @Test public void testCanSerialiseElementClass() throws SerialisationException { assertTrue(serialiser.canHandle(Entity.class)); } @Test public void testDeserialiseEmpty() throws SerialisationException { assertEquals(null, serialiser.deserialiseEmpty()); } @Test public void testPreserveObjectOrdering() throws SerialisationException { assertEquals(false, serialiser.preservesObjectOrdering()); } }
package com.liheng.study; /** * Created by dell on 2016/3/5. */ public class LightEntity { private float light; private String timestamp; public LightEntity(float light,String timestamp){ this.light=light; this.timestamp=timestamp; } public float getLight() { return light; } public void setLight(float light) { this.light = light; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } }
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.ws.addressing.policy; import com.sun.xml.internal.ws.api.addressing.AddressingVersion; import com.sun.xml.internal.ws.policy.AssertionSet; import com.sun.xml.internal.ws.policy.NestedPolicy; import com.sun.xml.internal.ws.policy.Policy; import com.sun.xml.internal.ws.policy.PolicyAssertion; import com.sun.xml.internal.ws.policy.PolicyException; import com.sun.xml.internal.ws.policy.PolicyMap; import com.sun.xml.internal.ws.policy.PolicyMapKey; import com.sun.xml.internal.ws.policy.jaxws.spi.PolicyFeatureConfigurator; import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger; import com.sun.xml.internal.ws.addressing.W3CAddressingMetadataConstants; import com.sun.xml.internal.ws.resources.ModelerMessages; import com.sun.xml.internal.bind.util.Which; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.logging.Level; import javax.xml.namespace.QName; import javax.xml.ws.WebServiceFeature; import javax.xml.ws.WebServiceException; import javax.xml.ws.soap.AddressingFeature; /** * This Policy extension configures the WSDLModel with AddressingFeature when Addressing assertions are present in the * PolicyMap. * * @author japod * @author Rama Pulavarthi */ public class AddressingFeatureConfigurator implements PolicyFeatureConfigurator { private static final PolicyLogger LOGGER = PolicyLogger.getLogger(AddressingFeatureConfigurator.class); private static final QName[] ADDRESSING_ASSERTIONS = { new QName(AddressingVersion.MEMBER.policyNsUri, "UsingAddressing")}; /** * Creates a new instance of AddressingFeatureConfigurator */ public AddressingFeatureConfigurator() { } public Collection<WebServiceFeature> getFeatures(final PolicyMapKey key, final PolicyMap policyMap) throws PolicyException { LOGGER.entering(key, policyMap); final Collection<WebServiceFeature> features = new LinkedList<WebServiceFeature>(); if ((key != null) && (policyMap != null)) { final Policy policy = policyMap.getEndpointEffectivePolicy(key); for (QName addressingAssertionQName : ADDRESSING_ASSERTIONS) { if ((policy != null) && policy.contains(addressingAssertionQName)) { final Iterator <AssertionSet> assertions = policy.iterator(); while(assertions.hasNext()){ final AssertionSet assertionSet = assertions.next(); final Iterator<PolicyAssertion> policyAssertion = assertionSet.iterator(); while(policyAssertion.hasNext()){ final PolicyAssertion assertion = policyAssertion.next(); if(assertion.getName().equals(addressingAssertionQName)){ final WebServiceFeature feature = AddressingVersion.getFeature(addressingAssertionQName.getNamespaceURI(), true, !assertion.isOptional()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Added addressing feature \"" + feature + "\" for element \"" + key + "\""); } features.add(feature); } // end-if non optional wsa assertion found } // next assertion } // next alternative } // end-if policy contains wsa assertion } //end foreach addr assertion // Deal with WS-Addressing 1.0 Metadata assertions if (policy != null && policy.contains(W3CAddressingMetadataConstants.WSAM_ADDRESSING_ASSERTION)) { for (AssertionSet assertions : policy) { for (PolicyAssertion assertion : assertions) { if (assertion.getName().equals(W3CAddressingMetadataConstants.WSAM_ADDRESSING_ASSERTION)) { NestedPolicy nestedPolicy = assertion.getNestedPolicy(); boolean requiresAnonymousResponses = false; boolean requiresNonAnonymousResponses = false; if (nestedPolicy != null) { requiresAnonymousResponses = nestedPolicy.contains(W3CAddressingMetadataConstants.WSAM_ANONYMOUS_NESTED_ASSERTION); requiresNonAnonymousResponses = nestedPolicy.contains(W3CAddressingMetadataConstants.WSAM_NONANONYMOUS_NESTED_ASSERTION); } if(requiresAnonymousResponses && requiresNonAnonymousResponses) { throw new WebServiceException("Only one among AnonymousResponses and NonAnonymousResponses can be nested in an Addressing assertion"); } final WebServiceFeature feature; try { if (requiresAnonymousResponses) { feature = new AddressingFeature(true, !assertion.isOptional(), AddressingFeature.Responses.ANONYMOUS); } else if (requiresNonAnonymousResponses) { feature = new AddressingFeature(true, !assertion.isOptional(), AddressingFeature.Responses.NON_ANONYMOUS); } else { feature = new AddressingFeature(true, !assertion.isOptional()); } } catch (NoSuchMethodError e) { throw LOGGER.logSevereException(new PolicyException(ModelerMessages.RUNTIME_MODELER_ADDRESSING_RESPONSES_NOSUCHMETHOD(toJar(Which.which(AddressingFeature.class))), e)); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Added addressing feature \"" + feature + "\" for element \"" + key + "\""); } features.add(feature); } } } } } LOGGER.exiting(features); return features; } /** * Given the URL String inside jar, returns the URL to the jar itself. */ private static String toJar(String url) { if(!url.startsWith("jar:")) return url; url = url.substring(4); // cut off jar: return url.substring(0,url.lastIndexOf('!')); // cut off everything after '!' } }
package top.chenqwwq.leetcode.weekly._248._2; import java.util.Arrays; /** * @author chen * @date 2021/7/4 **/ public class Solution { public int eliminateMaximum(int[] dist, int[] speed) { // 每个怪兽到城市的时间 final int n = dist.length; float[] times = new float[n]; for (int i = 0; i < n; i++) { times[i] = 1.0f * dist[i] / speed[i]; } Arrays.sort(times); int cnt = 0; for (float num : times) { if (cnt < num) { cnt++; } else { return cnt; } } return cnt; } }
package com.mail.coupon.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.mail.coupon.entity.SeckillSessionEntity; import com.mail.coupon.service.SeckillSessionService; import com.mail.common.utils.PageUtils; import com.mail.common.utils.R; /** * 秒杀活动场次 * * @author chenshun * @email sunlightcs@gmail.com * @date 2022-03-10 14:07:33 */ @RestController @RequestMapping("coupon/seckillsession") public class SeckillSessionController { @Autowired private SeckillSessionService seckillSessionService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("coupon:seckillsession:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = seckillSessionService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("coupon:seckillsession:info") public R info(@PathVariable("id") Long id){ SeckillSessionEntity seckillSession = seckillSessionService.getById(id); return R.ok().put("seckillSession", seckillSession); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("coupon:seckillsession:save") public R save(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.save(seckillSession); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("coupon:seckillsession:update") public R update(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.updateById(seckillSession); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("coupon:seckillsession:delete") public R delete(@RequestBody Long[] ids){ seckillSessionService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package org.apache.rya.accumulo.mr.tools; /* * 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. */ import org.apache.rya.api.resolver.impl.*; import org.junit.Test; import static org.apache.rya.accumulo.mr.tools.Upgrade322Tool.UpgradeObjectSerialization; import static org.junit.Assert.*; public class UpgradeObjectSerializationTest { @Test public void testBooleanUpgrade() throws Exception { String object = "true"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, BooleanRyaTypeResolver.BOOLEAN_LITERAL_MARKER); assertEquals("1", upgrade); } @Test public void testBooleanUpgradeFalse() throws Exception { String object = "false"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, BooleanRyaTypeResolver.BOOLEAN_LITERAL_MARKER); assertEquals("0", upgrade); } @Test public void testByteUpgradeLowest() throws Exception { String object = "-127"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, ByteRyaTypeResolver.LITERAL_MARKER); assertEquals("81", upgrade); } @Test public void testByteUpgradeHighest() throws Exception { String object = "127"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, ByteRyaTypeResolver.LITERAL_MARKER); assertEquals("7f", upgrade); } @Test public void testLongUpgrade() throws Exception { String object = "00000000000000000010"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, LongRyaTypeResolver.LONG_LITERAL_MARKER); assertEquals("800000000000000a", upgrade); } @Test public void testIntUpgrade() throws Exception { String object = "00000000010"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, IntegerRyaTypeResolver.INTEGER_LITERAL_MARKER); assertEquals("8000000a", upgrade); } @Test public void testDateTimeUpgrade() throws Exception { String object = "9223370726404375807"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, DateTimeRyaTypeResolver.DATETIME_LITERAL_MARKER); assertEquals("800001311cee3b00", upgrade); } @Test public void testDoubleUpgrade() throws Exception { String object = "00001 1.0"; final UpgradeObjectSerialization upgradeObjectSerialization = new UpgradeObjectSerialization(); final String upgrade = upgradeObjectSerialization .upgrade(object, DoubleRyaTypeResolver.DOUBLE_LITERAL_MARKER); assertEquals("c024000000000000", upgrade); } }
/*___Generated_by_IDEA___*/ package com.acintyo.reactnativeandroidperiodicfetch; /* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ public final class BuildConfig { public final static boolean DEBUG = Boolean.parseBoolean(null); }
package com.luv2code.hibernate.demo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.luv2code.hibernate.demo.entity.Student; public class UpdateStudentDemo { public static void main(String[] args) { // create session factory SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Student.class) .buildSessionFactory(); // create session Session session = factory.getCurrentSession(); // use the session object to save Java object try { int studentId = 1; // start transaction (every time in hibernate for a new CRUD operation) session.beginTransaction(); // retrieve student based on the id: primary key System.out.println("\nGetting student with id: " + studentId); Student myStudent = session.get(Student.class, studentId); System.out.println("Updating student... "); myStudent.setFirstName("Scooby"); // commit the transaction - updating to database (no needing to explicitly save or update) session.getTransaction().commit(); // NEW CODE session = factory.getCurrentSession(); session.beginTransaction(); // update email for all students System.out.println("Update email for all students"); session.createQuery("update Student set email='foo@gmail.com'").executeUpdate(); // commit the transaction session.getTransaction().commit(); System.out.println("Done!"); } finally { factory.close(); } } }
package org.javaz.queues.iface; import java.util.*; /** * */ public interface PartialSenderI extends Runnable { public static int DEFAULT_SEND_PERIOD = 60000; public static int DEFAULT_SMALL_DELAY_PERIOD = 10000; public static int DEFAULT_SEND_SIZE = 64; public static int DEFAULT_LOGS_COUNT = 32; /** * Stops this Thread */ public void stop(); /** * @param senderFeedI - feed, to which all data is pushed */ public void setSenderFeedI(PartialSenderFeedI senderFeedI); public PartialSenderFeedI getSenderFeedI(); /** * @param o - to be added * @return if object allowed to be added * <p> * Used to prevent data doubling, for example */ public boolean canBeAdded(Object o); /** * @param o - Object to calculate its hashCode * @return hashcode of object. If you adding complex data to sender * like Arrays or Collections, you should override hash calculation for them. * OR use objectHashCalculator */ public Object calculateObjectHash(Object o); /** * @param o - object to be added to Sender's queue */ public void addToQueue(Object o); /** * @param c - objects to be added to Sender's queue */ public void addToQueueAll(Collection c); /** * Internal method, called when next iteration of sending data happens. * It called sendByPortions, and can be overridden to provide any pre-logic * * @param toSend - all queue at moment of next tick happened */ public void preSendPartially(ArrayList toSend); /** * @param allData - data to be chunked and pushed to real send method * @return - results, if any */ public Collection sendByPortions(List allData); /** * Tuning part */ public int getChunkSize(); public void setChunkSize(int byHowMany); public int getSendPeriod(); public void setSendPeriod(int sendPeriod); public int getSmallDelayPeriod(); public void setSmallDelayPeriod(int smallDelayPeriod); public boolean isOnlyUniqueAllowed(); public void setOnlyUniqueAllowed(boolean onlyUnique); public int getMaxLogsCount(); public void setMaxLogsCount(int logsCount); public int getWaitDelayForMinimalSize(); public void setWaitDelayForMinimalSize(int waitDelayForMinimalSize); public boolean isRepeatFailedSend(); public void setRepeatFailedSend(boolean repeatFailedSend); /** * Getter and Setter for objectHashCalculator - * which can calculate hashes of complex Objects, liket Lists, Arrays, etc. */ public ObjectHashCalculator getObjectHashCalculator(); public void setObjectHashCalculator(ObjectHashCalculator hashCodeCalculator); /** * Methods useful for debugging/monitoring */ public ArrayList getLogs(); public int getSteps(); public int getCurrentStep(); public int getQueueLength(); public int getSendingQueueLength(); public long getStartWhenIteration(); public void startRotating(); }
package net.minecraft.client.renderer.entity.layers; import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.entity.IEntityRenderer; import net.minecraft.client.renderer.entity.model.WolfModel; import net.minecraft.entity.passive.WolfEntity; import net.minecraft.util.ResourceLocation; import net.optifine.Config; import net.optifine.CustomColors; public class WolfCollarLayer extends LayerRenderer<WolfEntity, WolfModel<WolfEntity>> { private static final ResourceLocation WOLF_COLLAR = new ResourceLocation("textures/entity/wolf/wolf_collar.png"); public WolfCollarLayer(IEntityRenderer<WolfEntity, WolfModel<WolfEntity>> rendererIn) { super(rendererIn); } public void render(MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int packedLightIn, WolfEntity entitylivingbaseIn, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch) { if (entitylivingbaseIn.isTamed() && !entitylivingbaseIn.isInvisible()) { float[] afloat = entitylivingbaseIn.getCollarColor().getColorComponentValues(); if (Config.isCustomColors()) { afloat = CustomColors.getWolfCollarColors(entitylivingbaseIn.getCollarColor(), afloat); } renderCutoutModel(this.getEntityModel(), WOLF_COLLAR, matrixStackIn, bufferIn, packedLightIn, entitylivingbaseIn, afloat[0], afloat[1], afloat[2]); } } }
package net.modificationstation.stationapi.impl.client.model; import com.google.common.primitives.Doubles; import lombok.Getter; import net.modificationstation.stationapi.api.util.Null; import net.modificationstation.stationapi.api.util.math.Direction; import java.util.*; import static net.modificationstation.stationapi.api.util.math.Direction.DOWN; import static net.modificationstation.stationapi.api.util.math.Direction.UP; public class JsonCuboidData { public final double[] from = Null.get(); public final double[] to = Null.get(); public final EnumMap<Direction, JsonFaceData> faces = Null.get(); @SuppressWarnings("FieldMayBeFinal") @Getter private boolean shade = true; public void postprocess() { Collections.reverse(Doubles.asList(from)); Collections.reverse(Doubles.asList(to)); double fromTmp = from[2]; from[2] = 16 - to[2]; to[2] = 16 - fromTmp; faces.forEach((direction, face) -> { if (face.localUVs == null) face.localUVs = getRotatedMatrix(direction); }); from[0] /= 16; from[1] /= 16; from[2] /= 16; to[0] /= 16; to[1] /= 16; to[2] /= 16; faces.forEach((direction, face) -> { if (direction == DOWN || direction == UP) face.rotation += 90; face.rotation = (face.rotation / 90) % 4; double tmp, startU1 = face.localUVs[0], startV1 = face.localUVs[1], endU1 = face.localUVs[2], endV1 = face.localUVs[3]; switch (direction) { case DOWN: if (face.rotation % 2 == 0) { tmp = startV1; startV1 = endV1; endV1 = tmp; } else { tmp = startU1; startU1 = endU1; endU1 = tmp; } double endU2 = endU1, startU2 = startU1, startV2 = startV1, endV2 = endV1; switch (face.rotation) { case 1: startV2 = startV1; endV2 = endV1; endU2 = startU1; startU2 = endU1; startV1 = endV1; endV1 = startV2; break; case 2: endU2 = endU1; startU2 = startU1; startV2 = startV1; endV2 = endV1; break; case 3: endU2 = endU1; startU2 = startU1; startU1 = endU1; endU1 = startU2; startV2 = endV1; endV2 = startV1; break; } face.localUVs = new double[] {startU1, startV1, endU1, endV1, startU2, startV2, endU2, endV2}; break; case UP: startU1 = faces.get(UP).localUVs[0]; startV1 = faces.get(UP).localUVs[1]; endU1 = faces.get(UP).localUVs[2]; endV1 = faces.get(UP).localUVs[3]; endU2 = endU1; startU2 = startU1; startV2 = startV1; endV2 = endV1; switch (faces.get(UP).rotation) { case 1: endU2 = endU1; startU2 = startU1; startU1 = endU1; endU1 = startU2; startV2 = endV1; endV2 = startV1; break; case 2: endU2 = endU1; startU2 = startU1; startV2 = startV1; endV2 = endV1; break; case 3: startV2 = startV1; endV2 = endV1; endU2 = startU1; startU2 = endU1; startV1 = endV1; endV1 = startV2; break; } face.localUVs = new double[] {startU1, startV1, endU1, endV1, startU2, startV2, endU2, endV2}; break; } }); } private double[] getRotatedMatrix(Direction direction) { switch(direction) { case DOWN: return new double[]{this.from[0], 16 - this.to[2], this.to[0], 16 - this.from[2]}; case UP: return new double[]{this.from[0], this.from[2], this.to[0], this.to[2]}; case NORTH: default: return new double[]{16 - this.to[0], 16 - this.to[1], 16 - this.from[0], 16 - this.from[1]}; case SOUTH: return new double[]{this.from[0], 16 - this.to[1], this.to[0], 16 - this.from[1]}; case WEST: return new double[]{this.from[2], 16 - this.to[1], this.to[2], 16 - this.from[1]}; case EAST: return new double[]{16 - this.to[2], 16 - this.to[1], 16 - this.from[2], 16 - this.from[1]}; } } }
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.imap.processor; import static org.apache.james.imap.ImapFixture.TAG; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.apache.james.core.Username; import org.apache.james.imap.api.ImapConstants; import org.apache.james.imap.api.message.response.ImapResponseMessage; import org.apache.james.imap.api.process.ImapProcessor.Responder; import org.apache.james.imap.encode.FakeImapSession; import org.apache.james.imap.message.request.DeleteACLRequest; import org.apache.james.imap.message.response.UnpooledStatusResponseFactory; import org.apache.james.mailbox.MailboxManager; import org.apache.james.mailbox.MailboxSession; import org.apache.james.mailbox.MailboxSessionUtil; import org.apache.james.mailbox.MessageManager; import org.apache.james.mailbox.MessageManager.MailboxMetaData; import org.apache.james.mailbox.MessageManager.MailboxMetaData.FetchGroup; import org.apache.james.mailbox.exception.MailboxException; import org.apache.james.mailbox.exception.MailboxNotFoundException; import org.apache.james.mailbox.model.MailboxACL; import org.apache.james.mailbox.model.MailboxACL.EntryKey; import org.apache.james.mailbox.model.MailboxPath; import org.apache.james.metrics.tests.RecordingMetricFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import reactor.core.publisher.Mono; /** * DeleteACLProcessor Test. */ class DeleteACLProcessorTest { private static final String MAILBOX_NAME = ImapConstants.INBOX_NAME; private static final Username USER_1 = Username.of("user1"); private FakeImapSession imapSession; private MailboxManager mailboxManager; private MailboxSession mailboxSession; private MailboxMetaData metaData; private DeleteACLRequest deleteACLRequest; private DeleteACLProcessor subject; private EntryKey user1Key; private MailboxPath path; private Responder responder; private ArgumentCaptor<ImapResponseMessage> argumentCaptor; @BeforeEach void setUp() throws Exception { path = MailboxPath.forUser(USER_1, MAILBOX_NAME); UnpooledStatusResponseFactory statusResponseFactory = new UnpooledStatusResponseFactory(); mailboxManager = mock(MailboxManager.class); when(mailboxManager.manageProcessing(any(), any())).thenAnswer((Answer<Mono>) invocation -> { Object[] args = invocation.getArguments(); return (Mono) args[0]; }); subject = new DeleteACLProcessor(mailboxManager, statusResponseFactory, new RecordingMetricFactory()); imapSession = new FakeImapSession(); mailboxSession = MailboxSessionUtil.create(USER_1); MessageManager messageManager = mock(MessageManager.class); metaData = mock(MailboxMetaData.class); responder = mock(Responder.class); imapSession.authenticated(); imapSession.setMailboxSession(mailboxSession); when(messageManager.getMetaData(any(MailboxMetaData.RecentMode.class), any(MailboxSession.class), any(FetchGroup.class))) .thenReturn(metaData); when(mailboxManager.getMailbox(any(MailboxPath.class), any(MailboxSession.class))) .thenReturn(messageManager); deleteACLRequest = new DeleteACLRequest(TAG, MAILBOX_NAME, USER_1.asString()); user1Key = EntryKey.deserialize(USER_1.asString()); argumentCaptor = ArgumentCaptor.forClass(ImapResponseMessage.class); } @Test void testNoListRight() throws Exception { when(mailboxManager.hasRight(path, MailboxACL.Right.Lookup, mailboxSession)) .thenReturn(false); subject.doProcess(deleteACLRequest, responder, imapSession).block(); verify(responder, times(1)).respond(argumentCaptor.capture()); verifyNoMoreInteractions(responder); assertThat(argumentCaptor.getAllValues()) .hasSize(1); assertThat(argumentCaptor.getAllValues().get(0)) .matches(StatusResponseTypeMatcher.NO_RESPONSE_MATCHER::matches); } @Test void testNoAdminRight() throws Exception { when(mailboxManager.hasRight(path, MailboxACL.Right.Lookup, mailboxSession)) .thenReturn(true); when(mailboxManager.hasRight(path, MailboxACL.Right.Administer, mailboxSession)) .thenReturn(false); subject.doProcess(deleteACLRequest, responder, imapSession).block(); verify(responder, times(1)).respond(argumentCaptor.capture()); verifyNoMoreInteractions(responder); assertThat(argumentCaptor.getAllValues()) .hasSize(1); assertThat(argumentCaptor.getAllValues().get(0)) .matches(StatusResponseTypeMatcher.NO_RESPONSE_MATCHER::matches); } @Test void testNonExistentMailboxName() throws Exception { when(mailboxManager.getMailbox(any(MailboxPath.class), any(MailboxSession.class))) .thenThrow(new MailboxNotFoundException("")); subject.doProcess(deleteACLRequest, responder, imapSession).block(); verify(responder, times(1)).respond(argumentCaptor.capture()); verifyNoMoreInteractions(responder); assertThat(argumentCaptor.getAllValues()) .hasSize(1); assertThat(argumentCaptor.getAllValues().get(0)) .matches(StatusResponseTypeMatcher.NO_RESPONSE_MATCHER::matches); } @Test void testDelete() throws MailboxException { MailboxACL acl = MailboxACL.OWNER_FULL_ACL; when(mailboxManager.hasRight(path, MailboxACL.Right.Lookup, mailboxSession)) .thenReturn(true); when(mailboxManager.hasRight(path, MailboxACL.Right.Administer, mailboxSession)) .thenReturn(true); when(metaData.getACL()).thenReturn(acl); subject.doProcess(deleteACLRequest, responder, imapSession).block(); verify(mailboxManager).applyRightsCommand(path, MailboxACL.command().key(user1Key).noRights().asReplacement(), mailboxSession); verify(responder, times(1)).respond(argumentCaptor.capture()); verifyNoMoreInteractions(responder); assertThat(argumentCaptor.getAllValues()) .hasSize(1); assertThat(argumentCaptor.getAllValues().get(0)) .matches(StatusResponseTypeMatcher.OK_RESPONSE_MATCHER::matches); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.test.actions; import org.apache.cordova.DroidGap; import android.app.Activity; import android.os.Bundle; public class CordovaActivity extends DroidGap { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/index.html"); } }
/* * Spreadsheet by Madhawa */ package exceptions; /** * * @author Madhawa */ /* This exception is raised when a given expression has a function with some parameters missing. Maybe the expression is incomplete. The raise condition is checked before each and every pop from the RPN stack */ public class MissingParameterException extends SpreadsheetException { @Override public String getMessage() { return "%Missing Parameter"; } }
package com.c2b.coin.account.service; import java.math.BigDecimal; import java.util.List; import com.c2b.coin.account.entity.AssetLog; import com.c2b.coin.account.entity.WithdrawAddressLog; import com.c2b.coin.common.AjaxResponse; public interface IWithdrawService { void addAddress(WithdrawAddressLog w); List<WithdrawAddressLog> getAddressList(Integer currencyType, long userId); void withdraw(long userId, int currencyType,String CurrencyName, String address, String remark, BigDecimal amount, String userName); AjaxResponse checkAssetPassword(long userId, String password,String verifyType,String verifyCode); void confirmCallback(String address, int currencyType, String userName, String hxId, BigDecimal amount, String orderNo); AjaxResponse checkPermission(long userId); boolean checkAmountLimit(String currencyName, BigDecimal amount); boolean checkAmountMax(Long userId, String currencyName, BigDecimal amount); void approvalWithDraw(int id,String currencyName, int status); List<AssetLog> getWithDrawList(); BigDecimal getDailyMax(String currencyName); BigDecimal getLimit(String currencyName); void deleteAddress(long id); }
package net.tenie.fx.component.container; import org.controlsfx.control.MasterDetailPane; import javafx.geometry.Side; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import net.tenie.Sqlucky.sdk.component.ComponentGetter; import net.tenie.Sqlucky.sdk.component.SqlcukyEditor; import net.tenie.Sqlucky.sdk.utility.CommonUtility; /* @author tenie */ public class OperateContainer { private HBox container; private MasterDetailPane treeAreaDetailPane; private DBinfoContainer dbinfoCtr; // 连接管理窗口 private CodeContainer codeCtr; // 代码编辑窗口 public OperateContainer() { container = new HBox(); codeCtr = new CodeContainer(); dbinfoCtr = new DBinfoContainer(); // SqlEditor.codeAreaRecover(); // 还原上次的sql代码 treeAreaDetailPane = new MasterDetailPane(Side.LEFT); treeAreaDetailPane.setShowDetailNode(true); treeAreaDetailPane.setMasterNode(codeCtr.getContainer()); treeAreaDetailPane.setDetailNode(dbinfoCtr.getContainer()); // treeAreaDetailPane.setDividerPosition(0.22); container.getChildren().add(treeAreaDetailPane); HBox.setHgrow(treeAreaDetailPane, Priority.ALWAYS); ComponentGetter.treeAreaDetailPane = treeAreaDetailPane; CommonUtility.fadeTransition(codeCtr.getContainer(), 1000); CommonUtility.fadeTransition(dbinfoCtr.getContainer(), 1000); } public HBox getContainer() { return container; } public void setContainer(HBox container) { this.container = container; } public MasterDetailPane getTreeAreaDetailPane() { return treeAreaDetailPane; } public void setTreeAreaDetailPane(MasterDetailPane treeAreaDetailPane) { this.treeAreaDetailPane = treeAreaDetailPane; } public DBinfoContainer getDbinfoCtr() { return dbinfoCtr; } public void setDbinfoCtr(DBinfoContainer dbinfoCtr) { this.dbinfoCtr = dbinfoCtr; } public CodeContainer getCodeCtr() { return codeCtr; } public void setCodeCtr(CodeContainer codeCtr) { this.codeCtr = codeCtr; } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /** Base Releasables package. */ package org.opensearch.common.lease;
package net.minecraft.util; import java.util.Random; import java.util.UUID; public class MathHelper { public static final float SQRT_2 = sqrt_float(2.0F); private static final int SIN_BITS = 12; private static final int SIN_MASK = 4095; private static final int SIN_COUNT = 4096; public static final float PI = (float)Math.PI; public static final float PI2 = ((float)Math.PI * 2F); public static final float PId2 = ((float)Math.PI / 2F); private static final float radFull = ((float)Math.PI * 2F); private static final float degFull = 360.0F; private static final float radToIndex = 651.8986F; private static final float degToIndex = 11.377778F; public static final float deg2Rad = 0.017453292F; private static final float[] SIN_TABLE_FAST = new float[4096]; public static boolean fastMath = false; /** * A table of sin values computed from 0 (inclusive) to 2*pi (exclusive), with steps of 2*PI / 65536. */ private static final float[] SIN_TABLE = new float[65536]; /** * Though it looks like an array, this is really more like a mapping. Key (index of this array) is the upper 5 bits * of the result of multiplying a 32-bit unsigned integer by the B(2, 5) De Bruijn sequence 0x077CB531. Value * (value stored in the array) is the unique index (from the right) of the leftmost one-bit in a 32-bit unsigned * integer that can cause the upper 5 bits to get that value. Used for highly optimized "find the log-base-2 of * this number" calculations. */ private static final int[] multiplyDeBruijnBitPosition; private static final double field_181163_d; private static final double[] field_181164_e; private static final double[] field_181165_f; private static final String __OBFID = "CL_00001496"; /** * sin looked up in a table */ public static float sin(float p_76126_0_) { return fastMath ? SIN_TABLE_FAST[(int)(p_76126_0_ * 651.8986F) & 4095] : SIN_TABLE[(int)(p_76126_0_ * 10430.378F) & 65535]; } /** * cos looked up in the sin table with the appropriate offset */ public static float cos(float value) { return fastMath ? SIN_TABLE_FAST[(int)((value + ((float)Math.PI / 2F)) * 651.8986F) & 4095] : SIN_TABLE[(int)(value * 10430.378F + 16384.0F) & 65535]; } public static float sqrt_float(float value) { return (float)Math.sqrt((double)value); } public static float sqrt_double(double value) { return (float)Math.sqrt(value); } /** * Returns the greatest integer less than or equal to the float argument */ public static int floor_float(float value) { int i = (int)value; return value < (float)i ? i - 1 : i; } /** * returns par0 cast as an int, and no greater than Integer.MAX_VALUE-1024 */ public static int truncateDoubleToInt(double value) { return (int)(value + 1024.0D) - 1024; } /** * Returns the greatest integer less than or equal to the double argument */ public static int floor_double(double value) { int i = (int)value; return value < (double)i ? i - 1 : i; } /** * Long version of floor_double */ public static long floor_double_long(double value) { long i = (long)value; return value < (double)i ? i - 1L : i; } public static int func_154353_e(double value) { return (int)(value >= 0.0D ? value : -value + 1.0D); } public static float abs(float value) { return value >= 0.0F ? value : -value; } /** * Returns the unsigned value of an int. */ public static int abs_int(int value) { return value >= 0 ? value : -value; } public static int ceiling_float_int(float value) { int i = (int)value; return value > (float)i ? i + 1 : i; } public static int ceiling_double_int(double value) { int i = (int)value; return value > (double)i ? i + 1 : i; } /** * Returns the value of the first parameter, clamped to be within the lower and upper limits given by the second and * third parameters. */ public static int clamp_int(int num, int min, int max) { return num < min ? min : (num > max ? max : num); } /** * Returns the value of the first parameter, clamped to be within the lower and upper limits given by the second and * third parameters */ public static float clamp_float(float num, float min, float max) { return num < min ? min : (num > max ? max : num); } public static double clamp_double(double num, double min, double max) { return num < min ? min : (num > max ? max : num); } public static double denormalizeClamp(double p_151238_0_, double p_151238_2_, double p_151238_4_) { return p_151238_4_ < 0.0D ? p_151238_0_ : (p_151238_4_ > 1.0D ? p_151238_2_ : p_151238_0_ + (p_151238_2_ - p_151238_0_) * p_151238_4_); } /** * Maximum of the absolute value of two numbers. */ public static double abs_max(double p_76132_0_, double p_76132_2_) { if (p_76132_0_ < 0.0D) { p_76132_0_ = -p_76132_0_; } if (p_76132_2_ < 0.0D) { p_76132_2_ = -p_76132_2_; } return p_76132_0_ > p_76132_2_ ? p_76132_0_ : p_76132_2_; } /** * Buckets an integer with specifed bucket sizes. Args: i, bucketSize */ public static int bucketInt(int p_76137_0_, int p_76137_1_) { return p_76137_0_ < 0 ? -((-p_76137_0_ - 1) / p_76137_1_) - 1 : p_76137_0_ / p_76137_1_; } public static int getRandomIntegerInRange(Random p_76136_0_, int p_76136_1_, int p_76136_2_) { return p_76136_1_ >= p_76136_2_ ? p_76136_1_ : p_76136_0_.nextInt(p_76136_2_ - p_76136_1_ + 1) + p_76136_1_; } public static float randomFloatClamp(Random p_151240_0_, float p_151240_1_, float p_151240_2_) { return p_151240_1_ >= p_151240_2_ ? p_151240_1_ : p_151240_0_.nextFloat() * (p_151240_2_ - p_151240_1_) + p_151240_1_; } public static double getRandomDoubleInRange(Random p_82716_0_, double p_82716_1_, double p_82716_3_) { return p_82716_1_ >= p_82716_3_ ? p_82716_1_ : p_82716_0_.nextDouble() * (p_82716_3_ - p_82716_1_) + p_82716_1_; } public static double average(long[] values) { long i = 0L; for (long j : values) { i += j; } return (double)i / (double)values.length; } public static boolean epsilonEquals(float p_180185_0_, float p_180185_1_) { return abs(p_180185_1_ - p_180185_0_) < 1.0E-5F; } public static int normalizeAngle(int p_180184_0_, int p_180184_1_) { return (p_180184_0_ % p_180184_1_ + p_180184_1_) % p_180184_1_; } /** * the angle is reduced to an angle between -180 and +180 by mod, and a 360 check */ public static float wrapAngleTo180_float(float value) { value = value % 360.0F; if (value >= 180.0F) { value -= 360.0F; } if (value < -180.0F) { value += 360.0F; } return value; } /** * the angle is reduced to an angle between -180 and +180 by mod, and a 360 check */ public static double wrapAngleTo180_double(double value) { value = value % 360.0D; if (value >= 180.0D) { value -= 360.0D; } if (value < -180.0D) { value += 360.0D; } return value; } /** * parses the string as integer or returns the second parameter if it fails */ public static int parseIntWithDefault(String p_82715_0_, int p_82715_1_) { try { return Integer.parseInt(p_82715_0_); } catch (Throwable var3) { return p_82715_1_; } } /** * parses the string as integer or returns the second parameter if it fails. this value is capped to par2 */ public static int parseIntWithDefaultAndMax(String p_82714_0_, int p_82714_1_, int p_82714_2_) { return Math.max(p_82714_2_, parseIntWithDefault(p_82714_0_, p_82714_1_)); } /** * parses the string as double or returns the second parameter if it fails. */ public static double parseDoubleWithDefault(String p_82712_0_, double p_82712_1_) { try { return Double.parseDouble(p_82712_0_); } catch (Throwable var4) { return p_82712_1_; } } public static double parseDoubleWithDefaultAndMax(String p_82713_0_, double p_82713_1_, double p_82713_3_) { return Math.max(p_82713_3_, parseDoubleWithDefault(p_82713_0_, p_82713_1_)); } /** * Returns the input value rounded up to the next highest power of two. */ public static int roundUpToPowerOfTwo(int value) { int i = value - 1; i = i | i >> 1; i = i | i >> 2; i = i | i >> 4; i = i | i >> 8; i = i | i >> 16; return i + 1; } /** * Is the given value a power of two? (1, 2, 4, 8, 16, ...) */ private static boolean isPowerOfTwo(int value) { return value != 0 && (value & value - 1) == 0; } /** * Uses a B(2, 5) De Bruijn sequence and a lookup table to efficiently calculate the log-base-two of the given * value. Optimized for cases where the input value is a power-of-two. If the input value is not a power-of-two, * then subtract 1 from the return value. */ private static int calculateLogBaseTwoDeBruijn(int value) { value = isPowerOfTwo(value) ? value : roundUpToPowerOfTwo(value); return multiplyDeBruijnBitPosition[(int)((long)value * 125613361L >> 27) & 31]; } /** * Efficiently calculates the floor of the base-2 log of an integer value. This is effectively the index of the * highest bit that is set. For example, if the number in binary is 0...100101, this will return 5. */ public static int calculateLogBaseTwo(int value) { return calculateLogBaseTwoDeBruijn(value) - (isPowerOfTwo(value) ? 0 : 1); } public static int func_154354_b(int p_154354_0_, int p_154354_1_) { if (p_154354_1_ == 0) { return 0; } else if (p_154354_0_ == 0) { return p_154354_1_; } else { if (p_154354_0_ < 0) { p_154354_1_ *= -1; } int i = p_154354_0_ % p_154354_1_; return i == 0 ? p_154354_0_ : p_154354_0_ + p_154354_1_ - i; } } public static int func_180183_b(float p_180183_0_, float p_180183_1_, float p_180183_2_) { return func_180181_b(floor_float(p_180183_0_ * 255.0F), floor_float(p_180183_1_ * 255.0F), floor_float(p_180183_2_ * 255.0F)); } public static int func_180181_b(int p_180181_0_, int p_180181_1_, int p_180181_2_) { int i = (p_180181_0_ << 8) + p_180181_1_; i = (i << 8) + p_180181_2_; return i; } public static int func_180188_d(int p_180188_0_, int p_180188_1_) { int i = (p_180188_0_ & 16711680) >> 16; int j = (p_180188_1_ & 16711680) >> 16; int k = (p_180188_0_ & 65280) >> 8; int l = (p_180188_1_ & 65280) >> 8; int i1 = (p_180188_0_ & 255) >> 0; int j1 = (p_180188_1_ & 255) >> 0; int k1 = (int)((float)i * (float)j / 255.0F); int l1 = (int)((float)k * (float)l / 255.0F); int i2 = (int)((float)i1 * (float)j1 / 255.0F); return p_180188_0_ & -16777216 | k1 << 16 | l1 << 8 | i2; } public static double func_181162_h(double p_181162_0_) { return p_181162_0_ - Math.floor(p_181162_0_); } public static long getPositionRandom(Vec3i pos) { return getCoordinateRandom(pos.getX(), pos.getY(), pos.getZ()); } public static long getCoordinateRandom(int x, int y, int z) { long i = (long)(x * 3129871) ^ (long)z * 116129781L ^ (long)y; i = i * i * 42317861L + i * 11L; return i; } public static UUID getRandomUuid(Random rand) { long i = rand.nextLong() & -61441L | 16384L; long j = rand.nextLong() & 4611686018427387903L | Long.MIN_VALUE; return new UUID(i, j); } public static double func_181160_c(double p_181160_0_, double p_181160_2_, double p_181160_4_) { return (p_181160_0_ - p_181160_2_) / (p_181160_4_ - p_181160_2_); } public static double func_181159_b(double p_181159_0_, double p_181159_2_) { double d0 = p_181159_2_ * p_181159_2_ + p_181159_0_ * p_181159_0_; if (Double.isNaN(d0)) { return Double.NaN; } else { boolean flag = p_181159_0_ < 0.0D; if (flag) { p_181159_0_ = -p_181159_0_; } boolean flag1 = p_181159_2_ < 0.0D; if (flag1) { p_181159_2_ = -p_181159_2_; } boolean flag2 = p_181159_0_ > p_181159_2_; if (flag2) { double d1 = p_181159_2_; p_181159_2_ = p_181159_0_; p_181159_0_ = d1; } double d9 = func_181161_i(d0); p_181159_2_ = p_181159_2_ * d9; p_181159_0_ = p_181159_0_ * d9; double d2 = field_181163_d + p_181159_0_; int i = (int)Double.doubleToRawLongBits(d2); double d3 = field_181164_e[i]; double d4 = field_181165_f[i]; double d5 = d2 - field_181163_d; double d6 = p_181159_0_ * d4 - p_181159_2_ * d5; double d7 = (6.0D + d6 * d6) * d6 * 0.16666666666666666D; double d8 = d3 + d7; if (flag2) { d8 = (Math.PI / 2D) - d8; } if (flag1) { d8 = Math.PI - d8; } if (flag) { d8 = -d8; } return d8; } } public static double func_181161_i(double p_181161_0_) { double d0 = 0.5D * p_181161_0_; long i = Double.doubleToRawLongBits(p_181161_0_); i = 6910469410427058090L - (i >> 1); p_181161_0_ = Double.longBitsToDouble(i); p_181161_0_ = p_181161_0_ * (1.5D - d0 * p_181161_0_ * p_181161_0_); return p_181161_0_; } public static int func_181758_c(float p_181758_0_, float p_181758_1_, float p_181758_2_) { int i = (int)(p_181758_0_ * 6.0F) % 6; float f = p_181758_0_ * 6.0F - (float)i; float f1 = p_181758_2_ * (1.0F - p_181758_1_); float f2 = p_181758_2_ * (1.0F - f * p_181758_1_); float f3 = p_181758_2_ * (1.0F - (1.0F - f) * p_181758_1_); float f4; float f5; float f6; switch (i) { case 0: f4 = p_181758_2_; f5 = f3; f6 = f1; break; case 1: f4 = f2; f5 = p_181758_2_; f6 = f1; break; case 2: f4 = f1; f5 = p_181758_2_; f6 = f3; break; case 3: f4 = f1; f5 = f2; f6 = p_181758_2_; break; case 4: f4 = f3; f5 = f1; f6 = p_181758_2_; break; case 5: f4 = p_181758_2_; f5 = f1; f6 = f2; break; default: throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + p_181758_0_ + ", " + p_181758_1_ + ", " + p_181758_2_); } int j = clamp_int((int)(f4 * 255.0F), 0, 255); int k = clamp_int((int)(f5 * 255.0F), 0, 255); int l = clamp_int((int)(f6 * 255.0F), 0, 255); return j << 16 | k << 8 | l; } static { for (int i = 0; i < 65536; ++i) { SIN_TABLE[i] = (float)Math.sin((double)i * Math.PI * 2.0D / 65536.0D); } for (int j = 0; j < 4096; ++j) { SIN_TABLE_FAST[j] = (float)Math.sin((double)(((float)j + 0.5F) / 4096.0F * ((float)Math.PI * 2F))); } for (int l = 0; l < 360; l += 90) { SIN_TABLE_FAST[(int)((float)l * 11.377778F) & 4095] = (float)Math.sin((double)((float)l * 0.017453292F)); } multiplyDeBruijnBitPosition = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; field_181163_d = Double.longBitsToDouble(4805340802404319232L); field_181164_e = new double[257]; field_181165_f = new double[257]; for (int k = 0; k < 257; ++k) { double d1 = (double)k / 256.0D; double d0 = Math.asin(d1); field_181165_f[k] = Math.cos(d0); field_181164_e[k] = d0; } } }
import java.util.Scanner; public class Zig_Zag_Arrays_03 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); String[] line1 = new String[n]; String[] line2 = new String[n]; for (int i = 0; i < n; i++) { String[] array = scanner.nextLine().split(" "); String firstElement = array[0]; String secondElement = array[1]; if ((i + 1) % 2 == 0) { line2[i] = firstElement; line1[i] = secondElement; } else { line1[i] = firstElement; line2[i] = secondElement; } } System.out.println(String.join(" ", line1)); System.out.println(String.join(" ", line2)); } }
package com.swmansion.gesturehandler; import android.os.Handler; import android.view.MotionEvent; public class TapGestureHandler extends GestureHandler<TapGestureHandler> { private static final long DEFAULT_MAX_DELAY_MS = 500; private static final long DEFAULT_MAX_DURATION_MS = 500; private static final int DEFAULT_MIN_NUMBER_OF_POINTERS = 1; private static final int DEFAULT_NUMBER_OF_TAPS = 1; private static float MAX_VALUE_IGNORE = Float.MIN_VALUE; private final Runnable mFailDelayed = new Runnable() { public void run() { TapGestureHandler.this.fail(); } }; private Handler mHandler; private float mLastX; private float mLastY; private long mMaxDelayMs = 500; private float mMaxDeltaX; private float mMaxDeltaY; private float mMaxDistSq; private long mMaxDurationMs = 500; private int mMinNumberOfPointers = 1; private int mNumberOfPointers = 1; private int mNumberOfTaps = 1; private float mOffsetX; private float mOffsetY; private float mStartX; private float mStartY; private int mTapsSoFar; public TapGestureHandler setNumberOfTaps(int i) { this.mNumberOfTaps = i; return this; } public TapGestureHandler setMaxDelayMs(long j) { this.mMaxDelayMs = j; return this; } public TapGestureHandler setMaxDurationMs(long j) { this.mMaxDurationMs = j; return this; } public TapGestureHandler setMaxDx(float f) { this.mMaxDeltaX = f; return this; } public TapGestureHandler setMaxDy(float f) { this.mMaxDeltaY = f; return this; } public TapGestureHandler setMaxDist(float f) { this.mMaxDistSq = f * f; return this; } public TapGestureHandler setMinNumberOfPointers(int i) { this.mMinNumberOfPointers = i; return this; } public TapGestureHandler() { float f = MAX_VALUE_IGNORE; this.mMaxDeltaX = f; this.mMaxDeltaY = f; this.mMaxDistSq = f; setShouldCancelWhenOutside(true); } private void startTap() { Handler handler = this.mHandler; if (handler == null) { this.mHandler = new Handler(); } else { handler.removeCallbacksAndMessages((Object) null); } this.mHandler.postDelayed(this.mFailDelayed, this.mMaxDurationMs); } private void endTap() { Handler handler = this.mHandler; if (handler == null) { this.mHandler = new Handler(); } else { handler.removeCallbacksAndMessages((Object) null); } int i = this.mTapsSoFar + 1; this.mTapsSoFar = i; if (i != this.mNumberOfTaps || this.mNumberOfPointers < this.mMinNumberOfPointers) { this.mHandler.postDelayed(this.mFailDelayed, this.mMaxDelayMs); return; } activate(); end(); } private boolean shouldFail() { float f = (this.mLastX - this.mStartX) + this.mOffsetX; if (this.mMaxDeltaX != MAX_VALUE_IGNORE && Math.abs(f) > this.mMaxDeltaX) { return true; } float f2 = (this.mLastY - this.mStartY) + this.mOffsetY; if (this.mMaxDeltaY != MAX_VALUE_IGNORE && Math.abs(f2) > this.mMaxDeltaY) { return true; } float f3 = (f2 * f2) + (f * f); float f4 = this.mMaxDistSq; if (f4 == MAX_VALUE_IGNORE || f3 <= f4) { return false; } return true; } /* access modifiers changed from: protected */ public void onHandle(MotionEvent motionEvent) { int state = getState(); int actionMasked = motionEvent.getActionMasked(); if (state == 0) { this.mOffsetX = 0.0f; this.mOffsetY = 0.0f; this.mStartX = motionEvent.getRawX(); this.mStartY = motionEvent.getRawY(); } if (actionMasked == 6 || actionMasked == 5) { this.mOffsetX += this.mLastX - this.mStartX; this.mOffsetY += this.mLastY - this.mStartY; this.mLastX = GestureUtils.getLastPointerX(motionEvent, true); float lastPointerY = GestureUtils.getLastPointerY(motionEvent, true); this.mLastY = lastPointerY; this.mStartX = this.mLastX; this.mStartY = lastPointerY; } else { this.mLastX = GestureUtils.getLastPointerX(motionEvent, true); this.mLastY = GestureUtils.getLastPointerY(motionEvent, true); } if (this.mNumberOfPointers < motionEvent.getPointerCount()) { this.mNumberOfPointers = motionEvent.getPointerCount(); } if (shouldFail()) { fail(); } else if (state == 0) { if (actionMasked == 0) { begin(); } startTap(); } else if (state != 2) { } else { if (actionMasked == 1) { endTap(); } else if (actionMasked == 0) { startTap(); } } } /* access modifiers changed from: protected */ public void onCancel() { Handler handler = this.mHandler; if (handler != null) { handler.removeCallbacksAndMessages((Object) null); } } /* access modifiers changed from: protected */ public void onReset() { this.mTapsSoFar = 0; this.mNumberOfPointers = 0; Handler handler = this.mHandler; if (handler != null) { handler.removeCallbacksAndMessages((Object) null); } } }
package com.len.entity; import java.io.Serializable; import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class SysJob implements Serializable { private String id; private String jobName; private String cron; private Boolean status; private String clazzPath; private String jobDesc; private String createBy; private Date createDate; private String updateBy; private Date updateDate; private static final long serialVersionUID = 1L; }
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.byteCodeViewer; import com.intellij.execution.filters.LineNumbersMapping; import com.intellij.openapi.Disposable; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.DocumentUtil; import javax.swing.*; import java.awt.*; /** * @author anna * @since 5/7/12 */ public class ByteCodeViewerComponent extends JPanel implements Disposable { private final Editor myEditor; public ByteCodeViewerComponent(Project project) { super(new BorderLayout()); final EditorFactory factory = EditorFactory.getInstance(); final Document doc = ((EditorFactoryImpl)factory).createDocument("", true, false); doc.setReadOnly(true); myEditor = factory.createEditor(doc, project); EditorHighlighterFactory editorHighlighterFactory = EditorHighlighterFactory.getInstance(); final SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(StdFileTypes.JAVA, project, null); ((EditorEx)myEditor).setHighlighter(editorHighlighterFactory.createEditorHighlighter(syntaxHighlighter, EditorColorsManager.getInstance().getGlobalScheme())); ((EditorEx)myEditor).setCaretVisible(true); final EditorSettings settings = myEditor.getSettings(); settings.setLineMarkerAreaShown(false); settings.setIndentGuidesShown(false); settings.setLineNumbersShown(false); settings.setFoldingOutlineShown(false); myEditor.setBorder(null); add(myEditor.getComponent(), BorderLayout.CENTER); } public void setText(final String bytecode) { setText(bytecode, 0); } public void setText(final String bytecode, PsiElement element) { int offset = 0; VirtualFile file = PsiUtilCore.getVirtualFile(element); if (file != null) { final Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { int lineNumber = document.getLineNumber(element.getTextOffset()); LineNumbersMapping mapping = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY); if (mapping != null) { int mappedLine = mapping.sourceToBytecode(lineNumber); while (mappedLine == -1 && lineNumber < document.getLineCount()) { mappedLine = mapping.sourceToBytecode(++lineNumber); } if (mappedLine > 0) { lineNumber = mappedLine; } } offset = bytecode.indexOf("LINENUMBER " + lineNumber); while (offset == -1 && lineNumber < document.getLineCount()) { offset = bytecode.indexOf("LINENUMBER " + (lineNumber++)); } } } setText(bytecode, Math.max(0, offset)); } public void setText(final String bytecode, final int offset) { DocumentUtil.writeInRunUndoTransparentAction(() -> { Document fragmentDoc = myEditor.getDocument(); fragmentDoc.setReadOnly(false); fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), bytecode); fragmentDoc.setReadOnly(true); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); }); } public String getText() { return myEditor.getDocument().getText(); } public JComponent getEditorComponent() { return myEditor.getContentComponent(); } @Override public void dispose() { EditorFactory.getInstance().releaseEditor(myEditor); } }
package core.popularidade; import core.Post; public class Normal implements ComportamentoSocial { /** * */ private static final long serialVersionUID = -7673162452689328855L; private static final int DELTA = 10; private static final int QTDPOSTSTOSHARE = 2; /** * Adiciona ao post recebido 10 pops. Incrementa o numero de curtidas do post. */ @Override public void curtir(Post post) { post.addPopularidade(DELTA); post.setCurtidas(post.getCurtidas()+1); } /** * Remove do post recebido 10 pops. Incrementa o numero de rejeições do post. */ @Override public void rejeitar(Post post) { post.removePopularidade(DELTA); post.setRejeicoes(post.getRejeicoes()+1); } @Override public int qtdParaCompartilhar() { return QTDPOSTSTOSHARE; } @Override public String toString() { return "Normal Pop"; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Examples.PingPong; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import neuLayout.Controller.UniverseController; import neuLayout.Model.TwoDimensionalMovement; import neuLayout.Model.actors.Actor; import neuLayout.Model.actors.ActorType; import neuLayout.Model.actors.CenterOfViewActor; import neuLayout.SettingsSingleton; /** * * @author andrewnyhus */ public class PingPongController extends UniverseController{ private Dimension table_size; private Actor leftPaddle, rightPaddle, leftScoreBox, rightScoreBox; public PingPongController(Dimension size){ super("Ping Pong", size, null); //the only reason that I did not use the table_size variable //in the call to the super constructor was because it would not //allow me to since the supercall needs to be the first line this.table_size = size; //set proper settings this.applyInitialSettings(); //set actors this.setupActors(); } public void setupActors(){ Actor middleLine, leftEdge, rightEdge; this.leftScoreBox = new Actor(ActorType.miscObject, new Point(this.table_size.width/2 - 75, 50), Color.white, new Rectangle(0, 0, 0, 0)); this.rightScoreBox = new Actor(ActorType.miscObject, new Point(this.table_size.width/2 + 75, 50), Color.white, new Rectangle(0, 0, 0, 0)); Rectangle paddleShape = new Rectangle(0, 0, 15, 80); int xPaddingForPaddles = 30; int yPaddlesInitLoc = (this.table_size.height/2) - (paddleShape.height/2); this.leftPaddle = new Actor(ActorType.miscObject, new Point(xPaddingForPaddles, yPaddlesInitLoc), Color.white, paddleShape); this.leftPaddle.setIdString("PADDLE_LEFT"); this.rightPaddle = new Actor(ActorType.miscObject, new Point(this.table_size.width - xPaddingForPaddles - paddleShape.width, yPaddlesInitLoc), Color.white, paddleShape); this.rightPaddle.setIdString("PADDLE_RIGHT"); Point ballPoint = new Point(this.table_size.width/2 - 10, this.table_size.height/2 - 10); Ball ball = new Ball(ballPoint, this.leftScoreBox, this.rightScoreBox); int leftX = SettingsSingleton.getInstance().getBorderThickness(); int leftY = SettingsSingleton.getInstance().getBorderThickness(); int edgesWidth = xPaddingForPaddles - leftX; int edgesHeight = this.table_size.height - (2*leftY); int rightX = this.table_size.width - edgesWidth - leftX; int rightY = leftY; leftEdge = new Actor(ActorType.miscObject, new Point(leftX, leftY), Color.black, new Rectangle(0, 0, edgesWidth, edgesHeight)); leftEdge.setIdString("LEFT_EDGE"); rightEdge = new Actor(ActorType.miscObject, new Point(rightX, rightY), Color.black, new Rectangle(0, 0, edgesWidth, edgesHeight)); rightEdge.setIdString("RIGHT_EDGE"); int middleLineThickness = 15; middleLine = new Actor(ActorType.miscObject, new Point(this.table_size.width/2 - middleLineThickness/2, leftY), Color.white, new Rectangle(0, 0, middleLineThickness, edgesHeight)); this.addActor(this.leftPaddle); this.addActor(this.rightPaddle); this.addActor(leftEdge); this.addActor(rightEdge); this.addActor(middleLine); this.addActor(ball); this.addActor(this.leftScoreBox); this.addActor(this.rightScoreBox); } private void applyInitialSettings() { SettingsSingleton.getInstance().setPerimeterColor(Color.white); SettingsSingleton.getInstance().setContainerBackgroundColor(Color.black); SettingsSingleton.getInstance().setLabelColor(Color.white); SettingsSingleton.getInstance().setScrollMode(SettingsSingleton.ViewScrollMode.DONT_SCROLL); } /** * Adds actor a to container if it would be valid there. * @param a */ public void addActor(Actor a){ //if a is valid in container if(this.getContainer().actorIsValidInContainerUniverse(a)){ //add a to container this.getContainer().addActorToContainer(a); } } @Override protected void addMenuBar(){ //we overrode this method here to remove the default menu bar } //Below is the implementation for the KeyListener methods. //These handle detection of various keys being pressed on the keyboard. //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= @Override public void keyTyped(KeyEvent e) { //ignore } /** * We will only pay attention to this KeyListener method, * this method fires when the user presses a key on their * keyboard, and the reason we must handle this event * is to respond to the keyboard either in attempts to pause, or * move their paddle. * @param e */ @Override public void keyPressed(KeyEvent e) { //store the int that corresponds to the key that was pressed int keycode = e.getKeyCode(); switch(keycode){ //if 's' key is pressed case KeyEvent.VK_S: if(this.leftPaddle.getVelocity().getYMovement() == 0){ this.leftPaddle.setVelocity(new TwoDimensionalMovement(0, 3)); }else if(this.leftPaddle.getVelocity().getYMovement() == -3){ this.leftPaddle.setVelocity(new TwoDimensionalMovement(0, 0)); } break; //if 'w' key is pressed case KeyEvent.VK_W: if(this.leftPaddle.getVelocity().getYMovement() == 3){ this.leftPaddle.setVelocity(new TwoDimensionalMovement(0, 0)); }else if(this.leftPaddle.getVelocity().getYMovement() == 0){ this.leftPaddle.setVelocity(new TwoDimensionalMovement(0, -3)); } break; //if down arrow is pressed case KeyEvent.VK_DOWN: if(this.rightPaddle.getVelocity().getYMovement() == 0){ this.rightPaddle.setVelocity(new TwoDimensionalMovement(0, 3)); }else if(this.rightPaddle.getVelocity().getYMovement() == -3){ this.rightPaddle.setVelocity(new TwoDimensionalMovement(0, 0)); } break; //if up arrow is pressed case KeyEvent.VK_UP: if(this.rightPaddle.getVelocity().getYMovement() == 3){ this.rightPaddle.setVelocity(new TwoDimensionalMovement(0, 0)); }else if(this.rightPaddle.getVelocity().getYMovement() == 0){ this.rightPaddle.setVelocity(new TwoDimensionalMovement(0, -3)); } break; } } @Override public void keyReleased(KeyEvent e) { //do nothing } //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.ml4j.nn; import java.util.List; import org.ml4j.nn.layers.Layer; /** * Base interface for classes representing a NeuralNetwork. * * @author Michael Lavelle * * @param <L> The type of Layer used within this NeuralNetwork * @param <C> The NeuralNetworkContext used with this NeuralNetwork * @param <N> The type of NeuralNetwork */ public interface LayeredNeuralNetwork<L extends Layer<?, ?, ?>, C extends LayeredNeuralNetworkContext, N extends LayeredNeuralNetwork<L, C, N>> extends NeuralNetwork<C, N> { /** * Obtains the list of Layers in this NeuralNetwork. * * @return the list of Layers in this NeuralNetwork */ List<L> getLayers(); /** * Obtains the number of Layers in this NeuralNetwork. * * @return the number of Layers in this NeuralNetwork */ int getNumberOfLayers(); /** * Obtains the Layer at the specified index in this NeuralNetwork. * * @param layerIndex The index of the Layer we wish to obtain * @return the Layer at the specified index in this NeuralNetwork */ L getLayer(int layerIndex); /** * Obtains the first Layer in the list of Layers in this NeuralNetwork. * * @return the first Layer in the list of Layers in this NeuralNetwork */ L getFirstLayer(); /** * Obtains the final Layer in the list of Layers in this NeuralNetwork. * * @return the final Layer in the list of Layers in this NeuralNetwork */ L getFinalLayer(); }
package me.bscal.betterfarming.common.database.blockdata.array; import me.bscal.betterfarming.common.database.blockdata.DataManager; import me.bscal.betterfarming.common.database.blockdata.IBlockDataBlock; import me.bscal.betterfarming.common.database.blockdata.IBlockDataWorld; import net.minecraft.server.MinecraftServer; import net.minecraft.server.world.ServerWorld; import java.util.function.Supplier; public class ArrayDataManager extends DataManager { public ArrayDataManager(MinecraftServer server, String id, Supplier<IBlockDataBlock> blockDataFactoryDefault) { super(server, id, blockDataFactoryDefault); } @Override public IBlockDataWorld SetupWorld(ServerWorld world) { var dataWorld = new ArrayDataWorld(id, world); worlds.add(dataWorld); return dataWorld; } }
package OOD.LinuxFind; import java.util.Stack; class FollowSymbolicLinkOptionParser extends Parser { @Override public String getName() { return "L"; } @Override public PlanNode parse(Stack<String> args) { return new FollowSymbolicLinkOption(); } }
package ir.doorbash.colyseus_chat; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.SparseArray; import android.widget.TextView; import com.stfalcon.chatkit.messages.MessageInput; import com.stfalcon.chatkit.messages.MessagesList; import com.stfalcon.chatkit.messages.MessagesListAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import io.colyseus.Client; import io.colyseus.Room; import io.colyseus.serializer.schema.Change; import ir.doorbash.colyseus_chat.classes.Message; import ir.doorbash.colyseus_chat.classes.MyState; import ir.doorbash.colyseus_chat.classes.User; public class MainActivity extends AppCompatActivity { // Constants public static final String ENDPOINT = "ws://192.168.1.134:3333"; // Views MessagesList messagesList; MessageInput inputView; TextView typing; // Variables Room<MyState> room; MessagesListAdapter<Message> adapter; final HashMap<String, User> users = new HashMap<>(); final SparseArray<Message> messages = new SparseArray<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messagesList = findViewById(R.id.messagesList); inputView = findViewById(R.id.input); typing = findViewById(R.id.typing); inputView.setInputListener(input -> { if (room != null) { LinkedHashMap<String, Object> data = new LinkedHashMap<>(); data.put("op", "message"); data.put("message", input.toString()); room.send(data); } return true; }); inputView.setTypingListener(new MessageInput.TypingListener() { @Override public void onStartTyping() { if (room != null) { LinkedHashMap<String, Object> data = new LinkedHashMap<>(); data.put("op", "typing"); data.put("status", true); room.send(data); } } @Override public void onStopTyping() { if (room != null) { LinkedHashMap<String, Object> data = new LinkedHashMap<>(); data.put("op", "typing"); data.put("status", false); room.send(data); } } }); connectToServer(); } private void connectToServer() { Client client = new Client(ENDPOINT); client.joinOrCreate("chat", MyState.class, room -> { System.out.println("joined chat"); this.room = room; runOnUiThread(() -> { adapter = new MessagesListAdapter<>(room.getSessionId(), null); messagesList.setAdapter(adapter); }); room.state.users.onAdd = (user, key) -> { synchronized (users) { users.put(key, user); } user.onChange = changes -> { for (Change change : changes) { if (change.field.equals("is_typing")) { System.out.println(room.getSessionId() + " : " + change); runOnUiThread(this::updateTypingUI); } } }; }; room.state.users.onRemove = (value, key) -> { synchronized (users) { users.remove(key); } }; room.state.messages.onAdd = (message, key) -> { synchronized (messages) { messages.put(key, message); } message.senderUser = room.state.users.get(message.sender); runOnUiThread(() -> adapter.addToStart(message, true)); }; room.state.messages.onRemove = (value, key) -> { synchronized (messages) { messages.remove(key); } }; room.state.users.triggerAll(); room.state.messages.triggerAll(); }, Throwable::printStackTrace); } private void updateTypingUI() { synchronized (users) { List<String> typingUsers = new ArrayList<>(); for (User user : users.values()) { if (user == null) continue; if (!user.id.equals(room.getSessionId()) && user.is_typing) { typingUsers.add(user.name); } } if (typingUsers.isEmpty()) { typing.setText(""); return; } StringBuilder text = new StringBuilder(); for (int i = 0; i < typingUsers.size(); i++) { if (i > 0) text.append(", "); text.append(typingUsers.get(i)); } if (typingUsers.size() == 1) { text.append(" is typing..."); typing.setText(text.toString()); } else { text.append(" are typing..."); typing.setText(text.toString()); } } } @Override protected void onDestroy() { if (room != null) room.leave(); super.onDestroy(); } }
package us.koller.cameraroll.preferences; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.rd.PageIndicatorView; import com.rd.animation.type.AnimationType; import us.koller.cameraroll.R; import us.koller.cameraroll.data.Settings; import us.koller.cameraroll.styles.Style; public class StylePreferenceDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { private int[] styles; int selectedStyle; private int whichButtonClicked; private Preference preference; public static StylePreferenceDialogFragment newInstance(Preference preference) { StylePreferenceDialogFragment fragment = new StylePreferenceDialogFragment(); fragment.setPreference(preference); return fragment; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { //get initial value from pref if (preference instanceof StylePreference) { selectedStyle = ((StylePreference) preference).getStyle(); } styles = getContext().getResources().getIntArray(R.array.style_values); @SuppressLint("InflateParams") View view = LayoutInflater.from(getContext()).inflate(R.layout.pref_dialog_style, null); ViewPager viewPager = view.findViewById(R.id.view_pager); viewPager.setAdapter(new ViewPagerAdapter(getContext())); viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { super.onPageSelected(position); selectedStyle = styles[position]; } }); int currentItem = 0; for (int i = 0; i < styles.length; i++) { if (styles[i] == selectedStyle) { currentItem = i; break; } } viewPager.setCurrentItem(currentItem); PageIndicatorView indicator = view.findViewById(R.id.indicator); indicator.setAnimationType(AnimationType.WORM); return new AlertDialog.Builder(getContext()) .setTitle(R.string.style) .setView(view) .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, null) .create(); } @Override public void onClick(DialogInterface dialogInterface, int i) { whichButtonClicked = i; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (whichButtonClicked == DialogInterface.BUTTON_POSITIVE && preference instanceof StylePreference) { StylePreference stylePreference = ((StylePreference) preference); stylePreference.setStyle(selectedStyle); Settings.getInstance(getActivity()).setStyle(selectedStyle); } } public void setPreference(Preference preference) { this.preference = preference; } public static class ViewPagerAdapter extends PagerAdapter { private Style[] styles; ViewPagerAdapter(Context context) { Settings settings = Settings.getInstance(context); int[] styleValues = context.getResources().getIntArray(R.array.style_values); styles = new Style[styleValues.length]; for (int i = 0; i < styles.length; i++) { styles[i] = settings.getStyleInstance(context, styleValues[i]); } } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { Style style = styles[position]; View view = style.createPrefDialogView(container); container.addView(view); return view; } @Override public int getCount() { return styles != null ? styles.length : 0; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view.equals(object); } @Override public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) { collection.removeView((View) view); } } }
package PROV.DM; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author tassio */ @Entity @Table(name = "ProvUsed") public class ProvUsed implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column private Integer idUsed; @Column @Temporal(TemporalType.TIMESTAMP) private Date timeUsed; @JoinColumn @ManyToOne private ProvActivity activity; @JoinColumn @ManyToOne private PROV.DM.ProvEntity entity; public ProvUsed() { } public ProvUsed(Integer idUsed) { this.idUsed = idUsed; } public Integer getIdUsed() { return idUsed; } public void setIdUsed(Integer idUsed) { this.idUsed = idUsed; } public Date getTimeUsed() { return timeUsed; } public void setTimeUsed(Date timeUsed) { this.timeUsed = timeUsed; } public ProvActivity getActivity() { return activity; } public void setActivity(ProvActivity activity) { this.activity = activity; } public PROV.DM.ProvEntity getEntity() { return entity; } public void setEntity(PROV.DM.ProvEntity entity) { this.entity = entity; } @Override public String toString() { return "ProvUsed{" + "idUsed=" + idUsed + ", timeUsed=" + timeUsed + ", activity=" + activity + ", entity=" + entity + '}'; } }
/* * Copyright 2011-2016 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.cloudwatch.model; import java.io.Serializable; /** * */ public class DeleteAlarmsResult implements Serializable, Cloneable { /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteAlarmsResult == false) return false; DeleteAlarmsResult other = (DeleteAlarmsResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteAlarmsResult clone() { try { return (DeleteAlarmsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package structures.cards; import akka.actor.ActorRef; import commands.BasicCommands; import structures.GameState; import structures.basic.Card; import structures.basic.EffectAnimation; import structures.basic.Tile; import structures.units.unitBlazeHound; import utils.BasicObjectBuilders; import utils.StaticConfFiles; public class cardBlazeHound extends Card{ public void UseCard(ActorRef out, GameState gameState, Tile tile) { BasicCommands.addPlayer1Notification(out, "summoned Blaze Hound on tile " + "[" + (tile.getTilex() + 1) + ", " + (tile.getTiley() + 1) + " ].", 3); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } EffectAnimation summon = BasicObjectBuilders.loadEffect(StaticConfFiles.f1_summon); BasicCommands.playEffectAnimation(out, summon, tile); try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();} gameState.addBotUnits(BasicObjectBuilders.loadUnit(StaticConfFiles.u_blaze_hound, gameState.getNewUnitID(), unitBlazeHound.class)); gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setPositionByTile(tile); BasicCommands.drawUnit(out, gameState.getBotUnits().get(gameState.getBotUnits().size()-1), tile); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setAttack(4); gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setHealth(3); BasicCommands.setUnitAttack(out, gameState.getBotUnits().get(gameState.getBotUnits().size()-1), 4); try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} BasicCommands.setUnitHealth(out, gameState.getBotUnits().get(gameState.getBotUnits().size()-1), 3); try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setTile(tile); tile.setUnit(gameState.getBotUnits().get(gameState.getBotUnits().size()-1)); gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setOwner("bot"); gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setName("Blaze Hound"); gameState.setNewUnitID(gameState.getNewUnitID()+1); //the first turn that the unit summoned, it cannot move or attack gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setAttacked(true); gameState.getBotUnits().get(gameState.getBotUnits().size()-1).setMoved(true); // minus player mana gameState.getBotPlayer().setMana(gameState.getBotPlayer().getMana() - this.manacost); BasicCommands.setPlayer2Mana(out, gameState.getBotPlayer()); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } //remove card gameState.setCurrentCard(null); gameState.getBotHand().remove(this); //both player draw 1 card if (!gameState.getHumanDeck().isEmpty()){ gameState.addHumanHand(gameState.getHumanDeck().get(0)); gameState.getHumanDeck().remove(0); BasicCommands.drawCard(out, gameState.getHumanHand().get(gameState.getHumanHand().size()-1), gameState.getHumanHand().size(),0); //show the card on the screen's humanHand part try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();} int j = 1; for (Card tmpCard : gameState.getHumanHand()){ BasicCommands.drawCard(out, tmpCard, j++,0); //show the card on the screen's humanHand part try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();} } } if (!gameState.getBotDeck().isEmpty()){ gameState.addBotHand(gameState.getBotDeck().get(0)); gameState.getBotDeck().remove(0); //remove the first card from botDeck } return; } }
package rocks.inspectit.shared.all.communication.comparator; import java.util.Comparator; import com.google.common.primitives.Longs; import rocks.inspectit.shared.all.cmr.service.ICachedDataService; import rocks.inspectit.shared.all.communication.data.TimerData; /** * Comparators for the {@link TimerData}. * * @author Ivan Senic * */ public enum TimerDataComparatorEnum implements IDataComparator<TimerData>, Comparator<TimerData> { /** * Sorts on the count. */ COUNT, /** * Sorts on the average duration. */ AVERAGE, /** * Sorts on the min duration. */ MIN, /** * Sorts on the max duration. */ MAX, /** * Sorts on the total duration. */ DURATION, /** * Sorts on the average CPU duration. */ CPUAVERAGE, /** * Sorts on the min CPU duration. */ CPUMIN, /** * Sorts on the max CPU duration. */ CPUMAX, /** * Sorts on the total CPU duration. */ CPUDURATION, /** * Sorts on the average exclusive duration. */ EXCLUSIVEAVERAGE, /** * Sorts on the min exclusive duration. */ EXCLUSIVEMIN, /** * Sorts on the max exclusive duration. */ EXCLUSIVEMAX, /** * Sorts on the total exclusive duration. */ EXCLUSIVEDURATION, /** * Sorts on charting true/false. */ CHARTING; /** * {@inheritDoc} */ @Override public int compare(TimerData o1, TimerData o2, ICachedDataService cachedDataService) { return compare(o1, o2); } /** * {@inheritDoc} */ @Override public int compare(TimerData o1, TimerData o2) { switch (this) { case COUNT: // Java6 does not have Long.compare return Longs.compare(o1.getCount(), o2.getCount()); case AVERAGE: return Double.compare(o1.getAverage(), o2.getAverage()); case MIN: return Double.compare(o1.getMin(), o2.getMin()); case MAX: return Double.compare(o1.getMax(), o2.getMax()); case DURATION: return Double.compare(o1.getDuration(), o2.getDuration()); case CPUAVERAGE: return Double.compare(o1.getCpuAverage(), o2.getCpuAverage()); case CPUMIN: return Double.compare(o1.getCpuMin(), o2.getCpuMin()); case CPUMAX: return Double.compare(o1.getCpuMax(), o2.getCpuMax()); case CPUDURATION: return Double.compare(o1.getCpuDuration(), o2.getCpuDuration()); case EXCLUSIVEAVERAGE: return Double.compare(o1.getExclusiveAverage(), o2.getExclusiveAverage()); case EXCLUSIVEMIN: return Double.compare(o1.getExclusiveMin(), o2.getExclusiveMin()); case EXCLUSIVEMAX: return Double.compare(o1.getExclusiveMax(), o2.getExclusiveMax()); case EXCLUSIVEDURATION: return Double.compare(o1.getExclusiveDuration(), o2.getExclusiveDuration()); case CHARTING: // Java5 does not have Boolean.compare return Boolean.valueOf(o1.isCharting()).compareTo(Boolean.valueOf(o2.isCharting())); default: return 0; } } }
// Copyright 2015-2021 Nkisi inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nkisi.util; import java.util.Collection; /** * Type that accumulates input values of type {@code I}, and binds an output * result of type {@code O}. */ public interface Builder<I, O> { /** * Adds a single input value to this builder, returning {@code true} if the * state of the builder changed. */ boolean add(I input); /** * Adds multiple input values to this builder, returning {@code true} if the * state of the builder changed. */ boolean addAll(Collection<? extends I> inputs); /** * Returns the output result of this builder. */ O bind(); }
package cn.yingsuo.im.server.request; /** * Created by AMing on 15/12/23. * Company RongCloud */ public class RegisterRequest { private String ni_name; private String password; private String code; private String tel; private String tui_tel; public RegisterRequest(String ni_name, String password, String code, String tel, String tui_tel) { this.ni_name = ni_name; this.password = password; this.code = code; this.tel = tel; this.tui_tel = tui_tel; } public String getNi_name() { return ni_name; } public void setNi_name(String ni_name) { this.ni_name = ni_name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getTui_tel() { return tui_tel; } public void setTui_tel(String tui_tel) { this.tui_tel = tui_tel; } }
package tools.commandline; /* * Extremely Compiler Collection. * Copyright (c) 2015-2020, Jianping Zeng. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.util.function.Consumer; /** * Command line option modifiers that can be used to modify the behavior of * command line option parsers.. * * @author Jianping Zeng * @version 0.4 */ public interface Modifier extends Consumer<Option<?>> { void apply(Option<?> opt); @Override default void accept(Option<?> option) { apply(option); } }
package seedu.jarvis.model; import javafx.beans.property.StringProperty; import javafx.collections.ObservableList; import seedu.jarvis.model.consultation.Consultation; import seedu.jarvis.model.masterycheck.MasteryCheck; import seedu.jarvis.model.mission.Mission; import seedu.jarvis.model.quest.Quest; import seedu.jarvis.model.student.Student; import seedu.jarvis.model.task.Task; /** * Unmodifiable view of an jarvis book */ public interface ReadOnlyAddressBook { /** * Returns an unmodifiable view of the persons list. * This list will not contain any duplicate persons. */ ObservableList<Student> getStudentList(); /** * Returns an unmodifiable view of the missions list. * This list will not contain any duplicate missions. */ ObservableList<Mission> getMissionList(); /** * Returns an unmodifiable view of the quest list. * This list will not contain any duplicate quests. */ ObservableList<Quest> getQuestList(); /** * Returns an unmodifiable view of the task list. * This list will not contain any duplicate tasks. */ ObservableList<Task> getTaskList(); /** Returns an unmodifiable view of the consultation list. * This list will not contain any duplicate consultations. */ ObservableList<Consultation> getConsultationList(); /** * Returns an unmodifiable view of the mastery check list. * This list will not contain any duplicate mastery checks. */ ObservableList<MasteryCheck> getMasteryChecksList(); /** * Returns the greeting of the user. */ StringProperty getGreeting(); }
package com.alvin.percobaanjawaban; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
package com.lody.virtual.server.interfaces; import android.os.RemoteException; import com.lody.virtual.remote.vloc.VCell; import com.lody.virtual.remote.vloc.VLocation; import java.util.List; /** * @author Lody */ public interface IVirtualLocationManager { int getMode(int userId, String pkg) throws RemoteException; void setMode(int userId, String pkg, int mode) throws RemoteException; void setCell(int userId, String pkg, VCell cell) throws RemoteException; void setAllCell(int userId, String pkg, List<VCell> cell) throws RemoteException; void setNeighboringCell(int userId, String pkg, List<VCell> cell) throws RemoteException; void setGlobalCell(VCell cell) throws RemoteException; void setGlobalAllCell(List<VCell> cell) throws RemoteException; void setGlobalNeighboringCell(List<VCell> cell) throws RemoteException; VCell getCell(int userId, String pkg) throws RemoteException; List<VCell> getAllCell(int userId, String pkg) throws RemoteException; List<VCell> getNeighboringCell(int userId, String pkg) throws RemoteException; void setLocation(int userId, String pkg, VLocation loc) throws RemoteException; VLocation getLocation(int userId, String pkg) throws RemoteException; void setGlobalLocation(VLocation loc) throws RemoteException; VLocation getGlobalLocation() throws RemoteException; }
package com.sly.designmodel.proxy; /** * RealSubject类,定义了Proxy所代理的真实实体 * @author sly * @time 2019年3月10日 */ public class RealSubject implements Subject { @Override public void request() { System.out.println("真实的请求!"); } }
package com.mindata.blockchain.socket.pbft.event; import com.mindata.blockchain.socket.pbft.msg.VoteMsg; import org.springframework.context.ApplicationEvent; /** * 消息已被验证,进入到Prepare集合中 * @author wuweifeng wrote on 2018/4/25. */ public class MsgPrepareEvent extends ApplicationEvent { public MsgPrepareEvent(VoteMsg source) { super(source); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.sql.execution.search; import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.RowSet; import org.elasticsearch.xpack.sql.session.SchemaRowSet; class SchemaDelegatingRowSet implements SchemaRowSet { private final Schema schema; private final RowSet delegate; SchemaDelegatingRowSet(Schema schema, RowSet delegate) { this.schema = schema; this.delegate = delegate; } @Override public Schema schema() { return schema; } @Override public boolean hasCurrentRow() { return delegate.hasCurrentRow(); } @Override public boolean advanceRow() { return delegate.advanceRow(); } @Override public int size() { return delegate.size(); } @Override public void reset() { delegate.reset(); } @Override public Object column(int index) { return delegate.column(index); } }
package org.owasp.dependencycheck.analyzer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.dependency.Dependency; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertTrue; import java.io.File; import org.owasp.dependencycheck.dependency.EvidenceType; /** * Unit tests for CocoaPodsAnalyzer and SwiftPackageManagerAnalyzer. * * @author Bianca Jiang * @author Jorge Mendes */ public class SwiftAnalyzersTest extends BaseTest { /** * The analyzer to test. */ private CocoaPodsAnalyzer podsAnalyzer; private SwiftPackageManagerAnalyzer spmAnalyzer; private SwiftPackageResolvedAnalyzer sprAnalyzer; /** * Correctly setup the analyzer for testing. * * @throws Exception thrown if there is a problem */ @Before @Override public void setUp() throws Exception { super.setUp(); podsAnalyzer = new CocoaPodsAnalyzer(); podsAnalyzer.initialize(getSettings()); podsAnalyzer.setFilesMatched(true); podsAnalyzer.prepare(null); spmAnalyzer = new SwiftPackageManagerAnalyzer(); spmAnalyzer.initialize(getSettings()); spmAnalyzer.setFilesMatched(true); spmAnalyzer.prepare(null); sprAnalyzer = new SwiftPackageResolvedAnalyzer(); sprAnalyzer.initialize(getSettings()); sprAnalyzer.setFilesMatched(true); sprAnalyzer.prepare(null); } /** * Cleanup the analyzer's temp files, etc. * * @throws Exception thrown if there is a problem */ @After @Override public void tearDown() throws Exception { podsAnalyzer.close(); podsAnalyzer = null; spmAnalyzer.close(); spmAnalyzer = null; super.tearDown(); } /** * Test of getName method, of class CocoaPodsAnalyzer. */ @Test public void testPodsGetName() { assertThat(podsAnalyzer.getName(), is("CocoaPods Package Analyzer")); } /** * Test of getName method, of class SwiftPackageManagerAnalyzer. */ @Test public void testSPMGetName() { assertThat(spmAnalyzer.getName(), is("SWIFT Package Manager Analyzer")); } /** * Test of supportsFiles method, of class CocoaPodsAnalyzer. */ @Test public void testPodsSupportsFiles() { assertThat(podsAnalyzer.accept(new File("test.podspec")), is(true)); assertThat(podsAnalyzer.accept(new File("Podfile.lock")), is(true)); } /** * Test of supportsFiles method, of class SwiftPackageManagerAnalyzer. */ @Test public void testSPMSupportsFiles() { assertThat(spmAnalyzer.accept(new File("Package.swift")), is(true)); assertThat(sprAnalyzer.accept(new File("Package.resolved")), is(true)); } /** * Test of analyze method, of class CocoaPodsAnalyzer. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testCocoaPodsPodfileAnalyzer() throws AnalysisException { final Engine engine = new Engine(getSettings()); final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "swift/cocoapods/Podfile.lock")); podsAnalyzer.analyze(result, engine); assertThat(engine.getDependencies().length, equalTo(9)); assertThat(engine.getDependencies()[0].getName(), equalTo("Bolts")); assertThat(engine.getDependencies()[0].getVersion(), equalTo("1.9.0")); assertThat(engine.getDependencies()[1].getName(), equalTo("Bolts/AppLinks")); assertThat(engine.getDependencies()[1].getVersion(), equalTo("1.9.0")); assertThat(engine.getDependencies()[2].getName(), equalTo("Bolts/Tasks")); assertThat(engine.getDependencies()[2].getVersion(), equalTo("1.9.0")); assertThat(engine.getDependencies()[3].getName(), equalTo("FBSDKCoreKit")); assertThat(engine.getDependencies()[3].getVersion(), equalTo("4.33.0")); assertThat(engine.getDependencies()[4].getName(), equalTo("FBSDKLoginKit")); assertThat(engine.getDependencies()[4].getVersion(), equalTo("4.33.0")); assertThat(engine.getDependencies()[5].getName(), equalTo("FirebaseCore")); assertThat(engine.getDependencies()[5].getVersion(), equalTo("5.0.1")); assertThat(engine.getDependencies()[6].getName(), equalTo("GoogleToolboxForMac/Defines")); assertThat(engine.getDependencies()[6].getVersion(), equalTo("2.1.4")); assertThat(engine.getDependencies()[7].getName(), equalTo("GoogleToolboxForMac/NSData+zlib")); assertThat(engine.getDependencies()[7].getVersion(), equalTo("2.1.4")); assertThat(engine.getDependencies()[8].getName(), equalTo("OCMock")); assertThat(engine.getDependencies()[8].getVersion(), equalTo("3.4.1")); } @Test public void testCocoaPodsPodspecAnalyzer() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "swift/cocoapods/EasyPeasy.podspec")); podsAnalyzer.analyze(result, null); final String vendorString = result.getEvidence(EvidenceType.VENDOR).toString(); assertThat(vendorString, containsString("Carlos Vidal")); assertThat(vendorString, containsString("https://github.com/nakiostudio/EasyPeasy")); assertThat(result.getEvidence(EvidenceType.PRODUCT).toString(), containsString("EasyPeasy")); assertThat(result.getEvidence(EvidenceType.VERSION).toString(), containsString("0.2.3")); assertThat(result.getName(), equalTo("EasyPeasy")); assertThat(result.getVersion(), equalTo("0.2.3")); assertThat(result.getDisplayFileName(), equalTo("EasyPeasy:0.2.3")); assertThat(result.getLicense(), containsString("MIT")); assertThat(result.getEcosystem(), equalTo(CocoaPodsAnalyzer.DEPENDENCY_ECOSYSTEM)); } /** * Test of analyze method, of class SwiftPackageManagerAnalyzer. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testSPMAnalyzer() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "swift/Gloss/Package.swift")); spmAnalyzer.analyze(result, null); assertThat(result.getEvidence(EvidenceType.PRODUCT).toString(), containsString("Gloss")); assertThat(result.getName(), equalTo("Gloss")); //TODO: when version processing is added, update the expected name. assertThat(result.getDisplayFileName(), equalTo("Gloss")); assertThat(result.getEcosystem(), equalTo(SwiftPackageManagerAnalyzer.DEPENDENCY_ECOSYSTEM)); } @Test public void testSPMResolvedAnalyzer() throws AnalysisException { final Engine engine = new Engine(getSettings()); final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "swift/spm/Package.resolved")); sprAnalyzer.analyze(result, engine); assertThat(engine.getDependencies().length, equalTo(3)); assertThat(engine.getDependencies()[0].getName(), equalTo("Alamofire")); assertThat(engine.getDependencies()[0].getVersion(), equalTo("5.4.3")); assertThat(engine.getDependencies()[1].getName(), equalTo("AlamofireImage")); assertThat(engine.getDependencies()[1].getVersion(), equalTo("4.2.0")); assertThat(engine.getDependencies()[2].getName(), equalTo("Facebook")); assertThat(engine.getDependencies()[2].getVersion(), equalTo("9.3.0")); } @Test public void testIsEnabledIsTrueByDefault() { assertTrue(spmAnalyzer.isEnabled()); assertTrue(sprAnalyzer.isEnabled()); } }
/* * ARISTOSTLE UNIVERSITY OF THESSALONIKI * Copyright (C) 2015 * Aristotle University of Thessaloniki * Department of Electrical & Computer Engineering * Division of Electronics & Computer Engineering * Intelligent Systems & Software Engineering Lab * * Project : reviews * WorkFile : * Compiler : * File Description : * Document Description: * Related Documents : * Note : * Programmer : RESTful MDE Engine created by Christoforos Zolotas * Contact : christopherzolotas@issel.ee.auth.gr */ package eu.fp7.scase.reviews.purchase; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.HeaderParam; import javax.ws.rs.DefaultValue; /* This class defines the web API of the individual purchase resource. It may handle PUT, GET and/or DELETE requests depending on the specific CIM of the service.*/ @Path("/account/{accountId}/purchase/{purchaseId}") public class JavapurchaseController{ @Context private UriInfo oApplicationUri; /* This function handles http GET requests and returns any response formatted as stated in the @Produces JAX-RS annotation below.*/ @Path("/") @GET @Produces("application/JSON") public JavapurchaseModel getpurchase(@HeaderParam("authorization") String authHeader, @PathParam("purchaseId") int purchaseId){ GetpurchaseHandler oGetpurchaseHandler = new GetpurchaseHandler(authHeader, purchaseId, oApplicationUri); return oGetpurchaseHandler.getJavapurchaseModel(); } /* This function handles http DELETE requests and returns any response formatted as stated in the @Produces JAX-RS annotation below.*/ @Path("/") @DELETE @Produces("application/JSON") public JavapurchaseModel deletepurchase(@HeaderParam("authorization") String authHeader, @PathParam("purchaseId") int purchaseId){ DeletepurchaseHandler oDeletepurchaseHandler = new DeletepurchaseHandler(authHeader, purchaseId, oApplicationUri); return oDeletepurchaseHandler.deleteJavapurchaseModel(); } }
package com.ucar.eser.front.controller.stats; import com.google.gson.JsonObject; import com.ucar.eser.core.jest.service.JestService; import io.searchbox.client.JestResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * * Created by wangjiulin on 2018/4/26. */ @Controller @RequestMapping("/stats") public class StatsController { private static final Logger LOG = LoggerFactory.getLogger(StatsController.class); @Autowired private JestService jestService; @RequestMapping(value = "/shards") @ResponseBody public Object shards(@RequestParam("indexName") String indexName, @RequestParam("clusterName") String clusterName) { try { JsonObject object; String targetPath = "/"+indexName+"/_stats?level=shards&human&pretty"; String targetMethod = "GET"; JestResult jestResult = (JestResult) jestService.httpProxy(clusterName,targetPath,targetMethod,null); object=jestResult.getJsonObject(); return object.toString(); } catch (Exception e) { LOG.error("获取shards 信息失败:",e); return e.getMessage(); } } }
// Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.metadata; import com.intellij.openapi.externalSystem.model.Key; import com.intellij.openapi.externalSystem.model.ProjectKeys; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData; import com.twitter.intellij.pants.model.TargetAddressInfo; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class TargetMetadata extends AbstractExternalEntityData { private static final long serialVersionUID = 1L; @NotNull public static final Key<TargetMetadata> KEY = Key.create(TargetMetadata.class, ProjectKeys.MODULE.getProcessingWeight() + 1); private final String myModuleName; private Set<String> myLibraryExcludes = Collections.emptySet(); private Set<String> myTargetAddresses = Collections.emptySet(); private Set<TargetAddressInfo> myTargetAddressInfoSet = Collections.emptySet(); public TargetMetadata(ProjectSystemId systemId, @NotNull String moduleName) { super(systemId); myModuleName = moduleName; } @NotNull public String getModuleName() { return myModuleName; } @NotNull public Set<String> getTargetAddresses() { return myTargetAddresses; } public void setTargetAddresses(Collection<String> targetAddresses) { myTargetAddresses = new HashSet<String>(targetAddresses); } public Set<TargetAddressInfo> getTargetAddressInfoSet() { return myTargetAddressInfoSet; } public void setTargetAddressInfoSet(Set<TargetAddressInfo> targetAddressInfoSet) { myTargetAddressInfoSet = new HashSet<TargetAddressInfo>(targetAddressInfoSet); } @NotNull public Set<String> getLibraryExcludes() { return myLibraryExcludes; } public void setLibraryExcludes(Set<String> libraryExcludes) { myLibraryExcludes = libraryExcludes; } }
package com.menu; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.manniu.manniu.R; /** * 实时视频菜单适配器 * @author jianhua * */ public class MenuAdapter extends BaseAdapter { private final List<MenuInfo> list; private final LayoutInflater inflater; public MenuAdapter(Context context,List<MenuInfo> list){ this.list=list; inflater=LayoutInflater.from(context); } public int getCount() { // TODO Auto-generated method stub return list.size(); } public Object getItem(int arg0) { // TODO Auto-generated method stub return list.get(arg0); } public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub View view=arg1; if (view==null) { view=inflater.inflate(R.layout.menu_item, null); } MenuInfo mInfo=list.get(arg0); ImageView iView=(ImageView)view.findViewById(R.id.item_image); TextView tView=(TextView)view.findViewById(R.id.item_text); iView.setImageResource(mInfo.imgsrc); tView.setText(mInfo.title); if (mInfo.ishide) { iView.setAlpha(80); } return view; } }