text
stringlengths 7
1.01M
|
|---|
/**
* Copyright 2009-2018 PrimeTek.
*
* 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.primefaces.model.menu;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Base implementation for model of a programmatic menu
*/
public class BaseMenuModel implements MenuModel, Serializable {
public static final String ID_SEPARATOR = "_";
private static final long serialVersionUID = 1L;
private List<MenuElement> elements;
public BaseMenuModel() {
elements = new ArrayList<>();
}
@Override
public void addElement(MenuElement element) {
elements.add(element);
}
@Override
public List<MenuElement> getElements() {
return elements;
}
@Override
public void generateUniqueIds() {
this.generateUniqueIds(getElements(), null);
}
private void generateUniqueIds(List<MenuElement> elements, String seed) {
if (elements == null || elements.isEmpty()) {
return;
}
int counter = 0;
for (MenuElement element : elements) {
String id = (seed == null) ? String.valueOf(counter++) : seed + ID_SEPARATOR + counter++;
element.setId(id);
if (element instanceof MenuGroup) {
generateUniqueIds(((MenuGroup) element).getElements(), id);
}
}
}
}
|
package org.hisp.dhis.period;
/*
* Copyright (c) 2004-2019, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* PeriodType for weekly Periods. A valid weekly Period has startDate set to
* Thursday and endDate set to Wednesday the same week, assuming Thursday is the first
* day and Wednesday is the last day of the week.
*
* @author Torgeir Lorange Ostby
*/
public class WeeklyThursdayPeriodType
extends WeeklyAbstractPeriodType
{
public static final String NAME = "WeeklyThursday";
public WeeklyThursdayPeriodType()
{
super( NAME, 4, "yyyyThuWn", "P7D", 7, "ThuW" );
}
}
|
package im.amomo.volley;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.Map;
/**
* Created by GoogolMo on 6/4/14.
*/
public interface OkStack {
Response performRequest(Request<?> request, Map<String, String> map) throws IOException, AuthFailureError;
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.02.19 um 02:35:56 PM CET
//
package org.onvif.ver10.media.wsdl;
import javax.xml.namespace.QName;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.annotation.XmlElementDecl;
import jakarta.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each Java content interface and Java element interface generated in the org.onvif.ver10.media.wsdl package.
* <p>
* An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java representation of XML content can consist of schema
* derived interfaces and classes representing the binding of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in this
* class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _Capabilities_QNAME = new QName("http://www.onvif.org/ver10/media/wsdl", "Capabilities");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onvif.ver10.media.wsdl
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link GetVideoSourceConfigurationOptionsResponse }
*
*/
public GetVideoSourceConfigurationOptionsResponse createGetVideoSourceConfigurationOptionsResponse() {
return new GetVideoSourceConfigurationOptionsResponse();
}
/**
* Create an instance of {@link GetCompatibleAudioEncoderConfigurations }
*
*/
public GetCompatibleAudioEncoderConfigurations createGetCompatibleAudioEncoderConfigurations() {
return new GetCompatibleAudioEncoderConfigurations();
}
/**
* Create an instance of {@link GetVideoEncoderConfigurationsResponse }
*
*/
public GetVideoEncoderConfigurationsResponse createGetVideoEncoderConfigurationsResponse() {
return new GetVideoEncoderConfigurationsResponse();
}
/**
* Create an instance of {@link GetVideoEncoderConfigurationResponse }
*
*/
public GetVideoEncoderConfigurationResponse createGetVideoEncoderConfigurationResponse() {
return new GetVideoEncoderConfigurationResponse();
}
/**
* Create an instance of {@link StartMulticastStreaming }
*
*/
public StartMulticastStreaming createStartMulticastStreaming() {
return new StartMulticastStreaming();
}
/**
* Create an instance of {@link GetMetadataConfigurationOptions }
*
*/
public GetMetadataConfigurationOptions createGetMetadataConfigurationOptions() {
return new GetMetadataConfigurationOptions();
}
/**
* Create an instance of {@link SetMetadataConfiguration }
*
*/
public SetMetadataConfiguration createSetMetadataConfiguration() {
return new SetMetadataConfiguration();
}
/**
* Create an instance of {@link SetOSDResponse }
*
*/
public SetOSDResponse createSetOSDResponse() {
return new SetOSDResponse();
}
/**
* Create an instance of {@link GetOSDResponse }
*
*/
public GetOSDResponse createGetOSDResponse() {
return new GetOSDResponse();
}
/**
* Create an instance of {@link GetVideoSourceConfiguration }
*
*/
public GetVideoSourceConfiguration createGetVideoSourceConfiguration() {
return new GetVideoSourceConfiguration();
}
/**
* Create an instance of {@link GetAudioSourceConfiguration }
*
*/
public GetAudioSourceConfiguration createGetAudioSourceConfiguration() {
return new GetAudioSourceConfiguration();
}
/**
* Create an instance of {@link GetCompatibleAudioDecoderConfigurations }
*
*/
public GetCompatibleAudioDecoderConfigurations createGetCompatibleAudioDecoderConfigurations() {
return new GetCompatibleAudioDecoderConfigurations();
}
/**
* Create an instance of {@link GetProfileResponse }
*
*/
public GetProfileResponse createGetProfileResponse() {
return new GetProfileResponse();
}
/**
* Create an instance of {@link GetVideoSourceConfigurations }
*
*/
public GetVideoSourceConfigurations createGetVideoSourceConfigurations() {
return new GetVideoSourceConfigurations();
}
/**
* Create an instance of {@link SetVideoEncoderConfiguration }
*
*/
public SetVideoEncoderConfiguration createSetVideoEncoderConfiguration() {
return new SetVideoEncoderConfiguration();
}
/**
* Create an instance of {@link AddAudioOutputConfiguration }
*
*/
public AddAudioOutputConfiguration createAddAudioOutputConfiguration() {
return new AddAudioOutputConfiguration();
}
/**
* Create an instance of {@link CreateProfile }
*
*/
public CreateProfile createCreateProfile() {
return new CreateProfile();
}
/**
* Create an instance of {@link AddAudioEncoderConfiguration }
*
*/
public AddAudioEncoderConfiguration createAddAudioEncoderConfiguration() {
return new AddAudioEncoderConfiguration();
}
/**
* Create an instance of {@link SetSynchronizationPointResponse }
*
*/
public SetSynchronizationPointResponse createSetSynchronizationPointResponse() {
return new SetSynchronizationPointResponse();
}
/**
* Create an instance of {@link DeleteProfile }
*
*/
public DeleteProfile createDeleteProfile() {
return new DeleteProfile();
}
/**
* Create an instance of {@link GetGuaranteedNumberOfVideoEncoderInstancesResponse }
*
*/
public GetGuaranteedNumberOfVideoEncoderInstancesResponse createGetGuaranteedNumberOfVideoEncoderInstancesResponse() {
return new GetGuaranteedNumberOfVideoEncoderInstancesResponse();
}
/**
* Create an instance of {@link RemoveAudioDecoderConfigurationResponse }
*
*/
public RemoveAudioDecoderConfigurationResponse createRemoveAudioDecoderConfigurationResponse() {
return new RemoveAudioDecoderConfigurationResponse();
}
/**
* Create an instance of {@link GetVideoAnalyticsConfiguration }
*
*/
public GetVideoAnalyticsConfiguration createGetVideoAnalyticsConfiguration() {
return new GetVideoAnalyticsConfiguration();
}
/**
* Create an instance of {@link SetVideoSourceModeResponse }
*
*/
public SetVideoSourceModeResponse createSetVideoSourceModeResponse() {
return new SetVideoSourceModeResponse();
}
/**
* Create an instance of {@link GetAudioEncoderConfigurationOptionsResponse }
*
*/
public GetAudioEncoderConfigurationOptionsResponse createGetAudioEncoderConfigurationOptionsResponse() {
return new GetAudioEncoderConfigurationOptionsResponse();
}
/**
* Create an instance of {@link GetAudioOutputConfiguration }
*
*/
public GetAudioOutputConfiguration createGetAudioOutputConfiguration() {
return new GetAudioOutputConfiguration();
}
/**
* Create an instance of {@link SetVideoSourceConfigurationResponse }
*
*/
public SetVideoSourceConfigurationResponse createSetVideoSourceConfigurationResponse() {
return new SetVideoSourceConfigurationResponse();
}
/**
* Create an instance of {@link SetVideoSourceConfiguration }
*
*/
public SetVideoSourceConfiguration createSetVideoSourceConfiguration() {
return new SetVideoSourceConfiguration();
}
/**
* Create an instance of {@link DeleteProfileResponse }
*
*/
public DeleteProfileResponse createDeleteProfileResponse() {
return new DeleteProfileResponse();
}
/**
* Create an instance of {@link GetProfilesResponse }
*
*/
public GetProfilesResponse createGetProfilesResponse() {
return new GetProfilesResponse();
}
/**
* Create an instance of {@link AddAudioOutputConfigurationResponse }
*
*/
public AddAudioOutputConfigurationResponse createAddAudioOutputConfigurationResponse() {
return new AddAudioOutputConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioSourcesResponse }
*
*/
public GetAudioSourcesResponse createGetAudioSourcesResponse() {
return new GetAudioSourcesResponse();
}
/**
* Create an instance of {@link RemoveAudioSourceConfigurationResponse }
*
*/
public RemoveAudioSourceConfigurationResponse createRemoveAudioSourceConfigurationResponse() {
return new RemoveAudioSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioOutputs }
*
*/
public GetAudioOutputs createGetAudioOutputs() {
return new GetAudioOutputs();
}
/**
* Create an instance of {@link GetAudioDecoderConfigurationsResponse }
*
*/
public GetAudioDecoderConfigurationsResponse createGetAudioDecoderConfigurationsResponse() {
return new GetAudioDecoderConfigurationsResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoSourceConfigurations }
*
*/
public GetCompatibleVideoSourceConfigurations createGetCompatibleVideoSourceConfigurations() {
return new GetCompatibleVideoSourceConfigurations();
}
/**
* Create an instance of {@link AddVideoSourceConfigurationResponse }
*
*/
public AddVideoSourceConfigurationResponse createAddVideoSourceConfigurationResponse() {
return new AddVideoSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioSourceConfigurationsResponse }
*
*/
public GetAudioSourceConfigurationsResponse createGetAudioSourceConfigurationsResponse() {
return new GetAudioSourceConfigurationsResponse();
}
/**
* Create an instance of {@link GetAudioOutputsResponse }
*
*/
public GetAudioOutputsResponse createGetAudioOutputsResponse() {
return new GetAudioOutputsResponse();
}
/**
* Create an instance of {@link GetVideoSourceConfigurationResponse }
*
*/
public GetVideoSourceConfigurationResponse createGetVideoSourceConfigurationResponse() {
return new GetVideoSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleAudioSourceConfigurations }
*
*/
public GetCompatibleAudioSourceConfigurations createGetCompatibleAudioSourceConfigurations() {
return new GetCompatibleAudioSourceConfigurations();
}
/**
* Create an instance of {@link CreateOSD }
*
*/
public CreateOSD createCreateOSD() {
return new CreateOSD();
}
/**
* Create an instance of {@link GetAudioEncoderConfigurationResponse }
*
*/
public GetAudioEncoderConfigurationResponse createGetAudioEncoderConfigurationResponse() {
return new GetAudioEncoderConfigurationResponse();
}
/**
* Create an instance of {@link GetMetadataConfiguration }
*
*/
public GetMetadataConfiguration createGetMetadataConfiguration() {
return new GetMetadataConfiguration();
}
/**
* Create an instance of {@link GetSnapshotUriResponse }
*
*/
public GetSnapshotUriResponse createGetSnapshotUriResponse() {
return new GetSnapshotUriResponse();
}
/**
* Create an instance of {@link SetAudioEncoderConfiguration }
*
*/
public SetAudioEncoderConfiguration createSetAudioEncoderConfiguration() {
return new SetAudioEncoderConfiguration();
}
/**
* Create an instance of {@link GetCompatibleMetadataConfigurationsResponse }
*
*/
public GetCompatibleMetadataConfigurationsResponse createGetCompatibleMetadataConfigurationsResponse() {
return new GetCompatibleMetadataConfigurationsResponse();
}
/**
* Create an instance of {@link AddVideoAnalyticsConfiguration }
*
*/
public AddVideoAnalyticsConfiguration createAddVideoAnalyticsConfiguration() {
return new AddVideoAnalyticsConfiguration();
}
/**
* Create an instance of {@link RemoveVideoSourceConfigurationResponse }
*
*/
public RemoveVideoSourceConfigurationResponse createRemoveVideoSourceConfigurationResponse() {
return new RemoveVideoSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetOSDsResponse }
*
*/
public GetOSDsResponse createGetOSDsResponse() {
return new GetOSDsResponse();
}
/**
* Create an instance of {@link GetAudioSourceConfigurationOptions }
*
*/
public GetAudioSourceConfigurationOptions createGetAudioSourceConfigurationOptions() {
return new GetAudioSourceConfigurationOptions();
}
/**
* Create an instance of {@link SetVideoAnalyticsConfigurationResponse }
*
*/
public SetVideoAnalyticsConfigurationResponse createSetVideoAnalyticsConfigurationResponse() {
return new SetVideoAnalyticsConfigurationResponse();
}
/**
* Create an instance of {@link GetVideoEncoderConfigurationOptionsResponse }
*
*/
public GetVideoEncoderConfigurationOptionsResponse createGetVideoEncoderConfigurationOptionsResponse() {
return new GetVideoEncoderConfigurationOptionsResponse();
}
/**
* Create an instance of {@link AddAudioSourceConfiguration }
*
*/
public AddAudioSourceConfiguration createAddAudioSourceConfiguration() {
return new AddAudioSourceConfiguration();
}
/**
* Create an instance of {@link GetVideoAnalyticsConfigurationsResponse }
*
*/
public GetVideoAnalyticsConfigurationsResponse createGetVideoAnalyticsConfigurationsResponse() {
return new GetVideoAnalyticsConfigurationsResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoSourceConfigurationsResponse }
*
*/
public GetCompatibleVideoSourceConfigurationsResponse createGetCompatibleVideoSourceConfigurationsResponse() {
return new GetCompatibleVideoSourceConfigurationsResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoEncoderConfigurations }
*
*/
public GetCompatibleVideoEncoderConfigurations createGetCompatibleVideoEncoderConfigurations() {
return new GetCompatibleVideoEncoderConfigurations();
}
/**
* Create an instance of {@link AddAudioSourceConfigurationResponse }
*
*/
public AddAudioSourceConfigurationResponse createAddAudioSourceConfigurationResponse() {
return new AddAudioSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioSources }
*
*/
public GetAudioSources createGetAudioSources() {
return new GetAudioSources();
}
/**
* Create an instance of {@link GetOSD }
*
*/
public GetOSD createGetOSD() {
return new GetOSD();
}
/**
* Create an instance of {@link GetVideoEncoderConfigurationOptions }
*
*/
public GetVideoEncoderConfigurationOptions createGetVideoEncoderConfigurationOptions() {
return new GetVideoEncoderConfigurationOptions();
}
/**
* Create an instance of {@link RemoveVideoAnalyticsConfiguration }
*
*/
public RemoveVideoAnalyticsConfiguration createRemoveVideoAnalyticsConfiguration() {
return new RemoveVideoAnalyticsConfiguration();
}
/**
* Create an instance of {@link SetVideoEncoderConfigurationResponse }
*
*/
public SetVideoEncoderConfigurationResponse createSetVideoEncoderConfigurationResponse() {
return new SetVideoEncoderConfigurationResponse();
}
/**
* Create an instance of {@link SetAudioDecoderConfiguration }
*
*/
public SetAudioDecoderConfiguration createSetAudioDecoderConfiguration() {
return new SetAudioDecoderConfiguration();
}
/**
* Create an instance of {@link StartMulticastStreamingResponse }
*
*/
public StartMulticastStreamingResponse createStartMulticastStreamingResponse() {
return new StartMulticastStreamingResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoAnalyticsConfigurations }
*
*/
public GetCompatibleVideoAnalyticsConfigurations createGetCompatibleVideoAnalyticsConfigurations() {
return new GetCompatibleVideoAnalyticsConfigurations();
}
/**
* Create an instance of {@link RemoveAudioSourceConfiguration }
*
*/
public RemoveAudioSourceConfiguration createRemoveAudioSourceConfiguration() {
return new RemoveAudioSourceConfiguration();
}
/**
* Create an instance of {@link GetAudioOutputConfigurationOptionsResponse }
*
*/
public GetAudioOutputConfigurationOptionsResponse createGetAudioOutputConfigurationOptionsResponse() {
return new GetAudioOutputConfigurationOptionsResponse();
}
/**
* Create an instance of {@link GetProfiles }
*
*/
public GetProfiles createGetProfiles() {
return new GetProfiles();
}
/**
* Create an instance of {@link SetAudioOutputConfiguration }
*
*/
public SetAudioOutputConfiguration createSetAudioOutputConfiguration() {
return new SetAudioOutputConfiguration();
}
/**
* Create an instance of {@link DeleteOSD }
*
*/
public DeleteOSD createDeleteOSD() {
return new DeleteOSD();
}
/**
* Create an instance of {@link SetAudioEncoderConfigurationResponse }
*
*/
public SetAudioEncoderConfigurationResponse createSetAudioEncoderConfigurationResponse() {
return new SetAudioEncoderConfigurationResponse();
}
/**
* Create an instance of {@link AddAudioEncoderConfigurationResponse }
*
*/
public AddAudioEncoderConfigurationResponse createAddAudioEncoderConfigurationResponse() {
return new AddAudioEncoderConfigurationResponse();
}
/**
* Create an instance of {@link DeleteOSDResponse }
*
*/
public DeleteOSDResponse createDeleteOSDResponse() {
return new DeleteOSDResponse();
}
/**
* Create an instance of {@link GetVideoSourceConfigurationOptions }
*
*/
public GetVideoSourceConfigurationOptions createGetVideoSourceConfigurationOptions() {
return new GetVideoSourceConfigurationOptions();
}
/**
* Create an instance of {@link GetVideoAnalyticsConfigurationResponse }
*
*/
public GetVideoAnalyticsConfigurationResponse createGetVideoAnalyticsConfigurationResponse() {
return new GetVideoAnalyticsConfigurationResponse();
}
/**
* Create an instance of {@link GetVideoSourceModesResponse }
*
*/
public GetVideoSourceModesResponse createGetVideoSourceModesResponse() {
return new GetVideoSourceModesResponse();
}
/**
* Create an instance of {@link VideoSourceMode }
*
*/
public VideoSourceMode createVideoSourceMode() {
return new VideoSourceMode();
}
/**
* Create an instance of {@link GetVideoSourceModes }
*
*/
public GetVideoSourceModes createGetVideoSourceModes() {
return new GetVideoSourceModes();
}
/**
* Create an instance of {@link GetGuaranteedNumberOfVideoEncoderInstances }
*
*/
public GetGuaranteedNumberOfVideoEncoderInstances createGetGuaranteedNumberOfVideoEncoderInstances() {
return new GetGuaranteedNumberOfVideoEncoderInstances();
}
/**
* Create an instance of {@link GetStreamUri }
*
*/
public GetStreamUri createGetStreamUri() {
return new GetStreamUri();
}
/**
* Create an instance of {@link AddPTZConfiguration }
*
*/
public AddPTZConfiguration createAddPTZConfiguration() {
return new AddPTZConfiguration();
}
/**
* Create an instance of {@link AddPTZConfigurationResponse }
*
*/
public AddPTZConfigurationResponse createAddPTZConfigurationResponse() {
return new AddPTZConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoAnalyticsConfigurationsResponse }
*
*/
public GetCompatibleVideoAnalyticsConfigurationsResponse createGetCompatibleVideoAnalyticsConfigurationsResponse() {
return new GetCompatibleVideoAnalyticsConfigurationsResponse();
}
/**
* Create an instance of {@link RemoveMetadataConfiguration }
*
*/
public RemoveMetadataConfiguration createRemoveMetadataConfiguration() {
return new RemoveMetadataConfiguration();
}
/**
* Create an instance of {@link GetAudioSourceConfigurationOptionsResponse }
*
*/
public GetAudioSourceConfigurationOptionsResponse createGetAudioSourceConfigurationOptionsResponse() {
return new GetAudioSourceConfigurationOptionsResponse();
}
/**
* Create an instance of {@link AddVideoSourceConfiguration }
*
*/
public AddVideoSourceConfiguration createAddVideoSourceConfiguration() {
return new AddVideoSourceConfiguration();
}
/**
* Create an instance of {@link GetAudioDecoderConfiguration }
*
*/
public GetAudioDecoderConfiguration createGetAudioDecoderConfiguration() {
return new GetAudioDecoderConfiguration();
}
/**
* Create an instance of {@link GetMetadataConfigurationOptionsResponse }
*
*/
public GetMetadataConfigurationOptionsResponse createGetMetadataConfigurationOptionsResponse() {
return new GetMetadataConfigurationOptionsResponse();
}
/**
* Create an instance of {@link GetServiceCapabilitiesResponse }
*
*/
public GetServiceCapabilitiesResponse createGetServiceCapabilitiesResponse() {
return new GetServiceCapabilitiesResponse();
}
/**
* Create an instance of {@link Capabilities }
*
*/
public Capabilities createCapabilities() {
return new Capabilities();
}
/**
* Create an instance of {@link GetVideoEncoderConfigurations }
*
*/
public GetVideoEncoderConfigurations createGetVideoEncoderConfigurations() {
return new GetVideoEncoderConfigurations();
}
/**
* Create an instance of {@link GetAudioOutputConfigurations }
*
*/
public GetAudioOutputConfigurations createGetAudioOutputConfigurations() {
return new GetAudioOutputConfigurations();
}
/**
* Create an instance of {@link GetOSDOptions }
*
*/
public GetOSDOptions createGetOSDOptions() {
return new GetOSDOptions();
}
/**
* Create an instance of {@link RemoveAudioOutputConfigurationResponse }
*
*/
public RemoveAudioOutputConfigurationResponse createRemoveAudioOutputConfigurationResponse() {
return new RemoveAudioOutputConfigurationResponse();
}
/**
* Create an instance of {@link GetOSDs }
*
*/
public GetOSDs createGetOSDs() {
return new GetOSDs();
}
/**
* Create an instance of {@link GetSnapshotUri }
*
*/
public GetSnapshotUri createGetSnapshotUri() {
return new GetSnapshotUri();
}
/**
* Create an instance of {@link GetVideoSourceConfigurationsResponse }
*
*/
public GetVideoSourceConfigurationsResponse createGetVideoSourceConfigurationsResponse() {
return new GetVideoSourceConfigurationsResponse();
}
/**
* Create an instance of {@link AddVideoEncoderConfiguration }
*
*/
public AddVideoEncoderConfiguration createAddVideoEncoderConfiguration() {
return new AddVideoEncoderConfiguration();
}
/**
* Create an instance of {@link RemoveVideoEncoderConfigurationResponse }
*
*/
public RemoveVideoEncoderConfigurationResponse createRemoveVideoEncoderConfigurationResponse() {
return new RemoveVideoEncoderConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioEncoderConfiguration }
*
*/
public GetAudioEncoderConfiguration createGetAudioEncoderConfiguration() {
return new GetAudioEncoderConfiguration();
}
/**
* Create an instance of {@link AddAudioDecoderConfiguration }
*
*/
public AddAudioDecoderConfiguration createAddAudioDecoderConfiguration() {
return new AddAudioDecoderConfiguration();
}
/**
* Create an instance of {@link AddMetadataConfigurationResponse }
*
*/
public AddMetadataConfigurationResponse createAddMetadataConfigurationResponse() {
return new AddMetadataConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleAudioOutputConfigurationsResponse }
*
*/
public GetCompatibleAudioOutputConfigurationsResponse createGetCompatibleAudioOutputConfigurationsResponse() {
return new GetCompatibleAudioOutputConfigurationsResponse();
}
/**
* Create an instance of {@link RemoveAudioOutputConfiguration }
*
*/
public RemoveAudioOutputConfiguration createRemoveAudioOutputConfiguration() {
return new RemoveAudioOutputConfiguration();
}
/**
* Create an instance of {@link GetCompatibleAudioSourceConfigurationsResponse }
*
*/
public GetCompatibleAudioSourceConfigurationsResponse createGetCompatibleAudioSourceConfigurationsResponse() {
return new GetCompatibleAudioSourceConfigurationsResponse();
}
/**
* Create an instance of {@link RemoveVideoSourceConfiguration }
*
*/
public RemoveVideoSourceConfiguration createRemoveVideoSourceConfiguration() {
return new RemoveVideoSourceConfiguration();
}
/**
* Create an instance of {@link GetAudioOutputConfigurationOptions }
*
*/
public GetAudioOutputConfigurationOptions createGetAudioOutputConfigurationOptions() {
return new GetAudioOutputConfigurationOptions();
}
/**
* Create an instance of {@link GetCompatibleAudioOutputConfigurations }
*
*/
public GetCompatibleAudioOutputConfigurations createGetCompatibleAudioOutputConfigurations() {
return new GetCompatibleAudioOutputConfigurations();
}
/**
* Create an instance of {@link CreateProfileResponse }
*
*/
public CreateProfileResponse createCreateProfileResponse() {
return new CreateProfileResponse();
}
/**
* Create an instance of {@link RemoveAudioDecoderConfiguration }
*
*/
public RemoveAudioDecoderConfiguration createRemoveAudioDecoderConfiguration() {
return new RemoveAudioDecoderConfiguration();
}
/**
* Create an instance of {@link GetAudioOutputConfigurationResponse }
*
*/
public GetAudioOutputConfigurationResponse createGetAudioOutputConfigurationResponse() {
return new GetAudioOutputConfigurationResponse();
}
/**
* Create an instance of {@link SetMetadataConfigurationResponse }
*
*/
public SetMetadataConfigurationResponse createSetMetadataConfigurationResponse() {
return new SetMetadataConfigurationResponse();
}
/**
* Create an instance of {@link RemoveVideoAnalyticsConfigurationResponse }
*
*/
public RemoveVideoAnalyticsConfigurationResponse createRemoveVideoAnalyticsConfigurationResponse() {
return new RemoveVideoAnalyticsConfigurationResponse();
}
/**
* Create an instance of {@link GetServiceCapabilities }
*
*/
public GetServiceCapabilities createGetServiceCapabilities() {
return new GetServiceCapabilities();
}
/**
* Create an instance of {@link SetAudioSourceConfiguration }
*
*/
public SetAudioSourceConfiguration createSetAudioSourceConfiguration() {
return new SetAudioSourceConfiguration();
}
/**
* Create an instance of {@link SetOSD }
*
*/
public SetOSD createSetOSD() {
return new SetOSD();
}
/**
* Create an instance of {@link AddVideoAnalyticsConfigurationResponse }
*
*/
public AddVideoAnalyticsConfigurationResponse createAddVideoAnalyticsConfigurationResponse() {
return new AddVideoAnalyticsConfigurationResponse();
}
/**
* Create an instance of {@link AddAudioDecoderConfigurationResponse }
*
*/
public AddAudioDecoderConfigurationResponse createAddAudioDecoderConfigurationResponse() {
return new AddAudioDecoderConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioOutputConfigurationsResponse }
*
*/
public GetAudioOutputConfigurationsResponse createGetAudioOutputConfigurationsResponse() {
return new GetAudioOutputConfigurationsResponse();
}
/**
* Create an instance of {@link RemoveAudioEncoderConfigurationResponse }
*
*/
public RemoveAudioEncoderConfigurationResponse createRemoveAudioEncoderConfigurationResponse() {
return new RemoveAudioEncoderConfigurationResponse();
}
/**
* Create an instance of {@link AddMetadataConfiguration }
*
*/
public AddMetadataConfiguration createAddMetadataConfiguration() {
return new AddMetadataConfiguration();
}
/**
* Create an instance of {@link GetVideoEncoderConfiguration }
*
*/
public GetVideoEncoderConfiguration createGetVideoEncoderConfiguration() {
return new GetVideoEncoderConfiguration();
}
/**
* Create an instance of {@link RemoveMetadataConfigurationResponse }
*
*/
public RemoveMetadataConfigurationResponse createRemoveMetadataConfigurationResponse() {
return new RemoveMetadataConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleVideoEncoderConfigurationsResponse }
*
*/
public GetCompatibleVideoEncoderConfigurationsResponse createGetCompatibleVideoEncoderConfigurationsResponse() {
return new GetCompatibleVideoEncoderConfigurationsResponse();
}
/**
* Create an instance of {@link SetAudioSourceConfigurationResponse }
*
*/
public SetAudioSourceConfigurationResponse createSetAudioSourceConfigurationResponse() {
return new SetAudioSourceConfigurationResponse();
}
/**
* Create an instance of {@link StopMulticastStreamingResponse }
*
*/
public StopMulticastStreamingResponse createStopMulticastStreamingResponse() {
return new StopMulticastStreamingResponse();
}
/**
* Create an instance of {@link SetAudioOutputConfigurationResponse }
*
*/
public SetAudioOutputConfigurationResponse createSetAudioOutputConfigurationResponse() {
return new SetAudioOutputConfigurationResponse();
}
/**
* Create an instance of {@link SetAudioDecoderConfigurationResponse }
*
*/
public SetAudioDecoderConfigurationResponse createSetAudioDecoderConfigurationResponse() {
return new SetAudioDecoderConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleAudioEncoderConfigurationsResponse }
*
*/
public GetCompatibleAudioEncoderConfigurationsResponse createGetCompatibleAudioEncoderConfigurationsResponse() {
return new GetCompatibleAudioEncoderConfigurationsResponse();
}
/**
* Create an instance of {@link GetAudioSourceConfigurations }
*
*/
public GetAudioSourceConfigurations createGetAudioSourceConfigurations() {
return new GetAudioSourceConfigurations();
}
/**
* Create an instance of {@link GetVideoSourcesResponse }
*
*/
public GetVideoSourcesResponse createGetVideoSourcesResponse() {
return new GetVideoSourcesResponse();
}
/**
* Create an instance of {@link GetAudioEncoderConfigurations }
*
*/
public GetAudioEncoderConfigurations createGetAudioEncoderConfigurations() {
return new GetAudioEncoderConfigurations();
}
/**
* Create an instance of {@link RemovePTZConfiguration }
*
*/
public RemovePTZConfiguration createRemovePTZConfiguration() {
return new RemovePTZConfiguration();
}
/**
* Create an instance of {@link CreateOSDResponse }
*
*/
public CreateOSDResponse createCreateOSDResponse() {
return new CreateOSDResponse();
}
/**
* Create an instance of {@link RemoveVideoEncoderConfiguration }
*
*/
public RemoveVideoEncoderConfiguration createRemoveVideoEncoderConfiguration() {
return new RemoveVideoEncoderConfiguration();
}
/**
* Create an instance of {@link SetSynchronizationPoint }
*
*/
public SetSynchronizationPoint createSetSynchronizationPoint() {
return new SetSynchronizationPoint();
}
/**
* Create an instance of {@link GetVideoAnalyticsConfigurations }
*
*/
public GetVideoAnalyticsConfigurations createGetVideoAnalyticsConfigurations() {
return new GetVideoAnalyticsConfigurations();
}
/**
* Create an instance of {@link GetAudioDecoderConfigurations }
*
*/
public GetAudioDecoderConfigurations createGetAudioDecoderConfigurations() {
return new GetAudioDecoderConfigurations();
}
/**
* Create an instance of {@link GetStreamUriResponse }
*
*/
public GetStreamUriResponse createGetStreamUriResponse() {
return new GetStreamUriResponse();
}
/**
* Create an instance of {@link GetAudioDecoderConfigurationOptions }
*
*/
public GetAudioDecoderConfigurationOptions createGetAudioDecoderConfigurationOptions() {
return new GetAudioDecoderConfigurationOptions();
}
/**
* Create an instance of {@link GetMetadataConfigurations }
*
*/
public GetMetadataConfigurations createGetMetadataConfigurations() {
return new GetMetadataConfigurations();
}
/**
* Create an instance of {@link GetMetadataConfigurationResponse }
*
*/
public GetMetadataConfigurationResponse createGetMetadataConfigurationResponse() {
return new GetMetadataConfigurationResponse();
}
/**
* Create an instance of {@link StopMulticastStreaming }
*
*/
public StopMulticastStreaming createStopMulticastStreaming() {
return new StopMulticastStreaming();
}
/**
* Create an instance of {@link SetVideoAnalyticsConfiguration }
*
*/
public SetVideoAnalyticsConfiguration createSetVideoAnalyticsConfiguration() {
return new SetVideoAnalyticsConfiguration();
}
/**
* Create an instance of {@link GetAudioDecoderConfigurationResponse }
*
*/
public GetAudioDecoderConfigurationResponse createGetAudioDecoderConfigurationResponse() {
return new GetAudioDecoderConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioEncoderConfigurationOptions }
*
*/
public GetAudioEncoderConfigurationOptions createGetAudioEncoderConfigurationOptions() {
return new GetAudioEncoderConfigurationOptions();
}
/**
* Create an instance of {@link GetAudioDecoderConfigurationOptionsResponse }
*
*/
public GetAudioDecoderConfigurationOptionsResponse createGetAudioDecoderConfigurationOptionsResponse() {
return new GetAudioDecoderConfigurationOptionsResponse();
}
/**
* Create an instance of {@link GetAudioEncoderConfigurationsResponse }
*
*/
public GetAudioEncoderConfigurationsResponse createGetAudioEncoderConfigurationsResponse() {
return new GetAudioEncoderConfigurationsResponse();
}
/**
* Create an instance of {@link GetCompatibleAudioDecoderConfigurationsResponse }
*
*/
public GetCompatibleAudioDecoderConfigurationsResponse createGetCompatibleAudioDecoderConfigurationsResponse() {
return new GetCompatibleAudioDecoderConfigurationsResponse();
}
/**
* Create an instance of {@link GetProfile }
*
*/
public GetProfile createGetProfile() {
return new GetProfile();
}
/**
* Create an instance of {@link AddVideoEncoderConfigurationResponse }
*
*/
public AddVideoEncoderConfigurationResponse createAddVideoEncoderConfigurationResponse() {
return new AddVideoEncoderConfigurationResponse();
}
/**
* Create an instance of {@link GetOSDOptionsResponse }
*
*/
public GetOSDOptionsResponse createGetOSDOptionsResponse() {
return new GetOSDOptionsResponse();
}
/**
* Create an instance of {@link GetMetadataConfigurationsResponse }
*
*/
public GetMetadataConfigurationsResponse createGetMetadataConfigurationsResponse() {
return new GetMetadataConfigurationsResponse();
}
/**
* Create an instance of {@link SetVideoSourceMode }
*
*/
public SetVideoSourceMode createSetVideoSourceMode() {
return new SetVideoSourceMode();
}
/**
* Create an instance of {@link RemovePTZConfigurationResponse }
*
*/
public RemovePTZConfigurationResponse createRemovePTZConfigurationResponse() {
return new RemovePTZConfigurationResponse();
}
/**
* Create an instance of {@link GetAudioSourceConfigurationResponse }
*
*/
public GetAudioSourceConfigurationResponse createGetAudioSourceConfigurationResponse() {
return new GetAudioSourceConfigurationResponse();
}
/**
* Create an instance of {@link GetCompatibleMetadataConfigurations }
*
*/
public GetCompatibleMetadataConfigurations createGetCompatibleMetadataConfigurations() {
return new GetCompatibleMetadataConfigurations();
}
/**
* Create an instance of {@link RemoveAudioEncoderConfiguration }
*
*/
public RemoveAudioEncoderConfiguration createRemoveAudioEncoderConfiguration() {
return new RemoveAudioEncoderConfiguration();
}
/**
* Create an instance of {@link GetVideoSources }
*
*/
public GetVideoSources createGetVideoSources() {
return new GetVideoSources();
}
/**
* Create an instance of {@link VideoSourceModeExtension }
*
*/
public VideoSourceModeExtension createVideoSourceModeExtension() {
return new VideoSourceModeExtension();
}
/**
* Create an instance of {@link StreamingCapabilities }
*
*/
public StreamingCapabilities createStreamingCapabilities() {
return new StreamingCapabilities();
}
/**
* Create an instance of {@link ProfileCapabilities }
*
*/
public ProfileCapabilities createProfileCapabilities() {
return new ProfileCapabilities();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Capabilities }{@code >}
*
*/
@XmlElementDecl(namespace = "http://www.onvif.org/ver10/media/wsdl", name = "Capabilities")
public JAXBElement<Capabilities> createCapabilities(Capabilities value) {
return new JAXBElement<Capabilities>(_Capabilities_QNAME, Capabilities.class, null, value);
}
}
|
package ysomap.common.util;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
/**
* @author wh1t3P1g
* @since 2020/2/19
*/
public class ColorStyle {
public static String makeWordRed(String word){
return new AttributedStringBuilder()
.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.RED))
.append(word)
.style(AttributedStyle.DEFAULT)
.toAnsi();
}
public static String makeWordRedAndBoldAndUnderline(String word){
return new AttributedStringBuilder()
.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.RED))
.style(AttributedStyle::bold)
.style(AttributedStyle::underline)
.append(word)
.style(AttributedStyle::underlineOff)
.style(AttributedStyle::boldOff)
.toAnsi();
}
public static String makeWordGreen(String word){
return new AttributedStringBuilder()
.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN))
.append(word)
.style(AttributedStyle.DEFAULT)
.toAnsi();
}
public static String makeWordBold(String word){
return new AttributedStringBuilder()
.style(AttributedStyle::bold)
.append(word)
.style(AttributedStyle::boldOff)
.toAnsi();
}
public static String makeWordBoldAndUnderline(String word){
return new AttributedStringBuilder()
.style(AttributedStyle::bold)
.style(AttributedStyle::underline)
.append(word)
.style(AttributedStyle::underlineOff)
.style(AttributedStyle::boldOff)
.toAnsi();
}
}
|
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.ignite.yardstick.cache;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.yardstick.cache.model.Organization;
import org.apache.ignite.yardstick.cache.model.Person;
import org.yardstickframework.BenchmarkConfiguration;
import static org.yardstickframework.BenchmarkUtils.println;
/**
* Ignite benchmark that performs query operations with joins.
*/
public class IgniteSqlQueryJoinBenchmark extends IgniteCacheAbstractBenchmark<Integer, Object> {
/** {@inheritDoc} */
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
println(cfg, "Populating query data...");
loadCachesData();
}
/** {@inheritDoc} */
@Override protected void loadCacheData(String cacheName) {
if (args.range() < 100)
throw new IllegalArgumentException("Invalid range: " + args.range());
try (IgniteDataStreamer<Object, Object> dataLdr = ignite().dataStreamer(cacheName)) {
final int orgRange = args.range() / 10;
// Populate organizations.
for (int i = 0; i < orgRange && !Thread.currentThread().isInterrupted(); i++)
dataLdr.addData(i, new Organization(i, "org" + i));
dataLdr.flush();
// Populate persons.
for (int i = orgRange; i < orgRange + args.range() && !Thread.currentThread().isInterrupted(); i++) {
Person p = new Person(i, nextRandom(orgRange), "firstName" + i, "lastName" + i, (i - orgRange) * 1000);
dataLdr.addData(i, p);
if (i % 100000 == 0)
println(cfg, "Populated persons: " + i);
}
}
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
double salary = ThreadLocalRandom.current().nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Collection<List<?>> lists = executeQueryJoin(salary, maxSalary);
for (List<?> l : lists) {
double sal = (Double)l.get(4);
if (sal < salary || sal > maxSalary) {
Person p = new Person();
p.setId((Integer)l.get(0));
p.setOrganizationId((Integer)l.get(1));
p.setFirstName((String)l.get(2));
p.setLastName((String)l.get(3));
p.setSalary(sal);
throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
", person=" + p + ']');
}
}
return true;
}
/**
* @param minSalary Min salary.
* @param maxSalary Max salary.
* @return Query results.
* @throws Exception If failed.
*/
private Collection<List<?>> executeQueryJoin(double minSalary, double maxSalary) throws Exception {
IgniteCache<Integer, Object> cache = cacheForOperation(true);
SqlFieldsQuery qry = new SqlFieldsQuery(
"select p.id, p.orgId, p.firstName, p.lastName, p.salary, o.name " +
"from Person p " +
"left join Organization o " +
"on p.id = o.id " +
"where salary >= ? and salary <= ?");
qry.setArgs(minSalary, maxSalary);
return cache.query(qry).getAll();
}
/** {@inheritDoc} */
@Override protected IgniteCache<Integer, Object> cache() {
return ignite().cache("query");
}
}
|
package crc643f46942d9dd1fff9;
public class EndSnapHelper
extends crc643f46942d9dd1fff9.EdgeSnapHelper
implements
mono.android.IGCUserPeer
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_calculateDistanceToFinalSnap:(Landroid/support/v7/widget/RecyclerView$LayoutManager;Landroid/view/View;)[I:GetCalculateDistanceToFinalSnap_Landroid_support_v7_widget_RecyclerView_LayoutManager_Landroid_view_View_Handler\n" +
"n_findSnapView:(Landroid/support/v7/widget/RecyclerView$LayoutManager;)Landroid/view/View;:GetFindSnapView_Landroid_support_v7_widget_RecyclerView_LayoutManager_Handler\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.EndSnapHelper, Xamarin.Forms.Platform.Android", EndSnapHelper.class, __md_methods);
}
public EndSnapHelper ()
{
super ();
if (getClass () == EndSnapHelper.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.EndSnapHelper, Xamarin.Forms.Platform.Android", "", this, new java.lang.Object[] { });
}
public int[] calculateDistanceToFinalSnap (android.support.v7.widget.RecyclerView.LayoutManager p0, android.view.View p1)
{
return n_calculateDistanceToFinalSnap (p0, p1);
}
private native int[] n_calculateDistanceToFinalSnap (android.support.v7.widget.RecyclerView.LayoutManager p0, android.view.View p1);
public android.view.View findSnapView (android.support.v7.widget.RecyclerView.LayoutManager p0)
{
return n_findSnapView (p0);
}
private native android.view.View n_findSnapView (android.support.v7.widget.RecyclerView.LayoutManager p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
package uk.ac.imperial.doc.masspa.gui.menus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import uk.ac.imperial.doc.masspa.gui.MASSPAEditorMain;
import uk.ac.imperial.doc.masspa.gui.interfaces.ITabController;
import uk.ac.imperial.doc.masspa.gui.util.Shortcuts;
import uk.ac.imperial.doc.masspa.language.Labels;
/**
* The edit menu
*/
public class JEditMenu extends JMainMenu
{
private static final long serialVersionUID = 9198681361850812125L;
public final JMenuItem m_mntmCopy;
public final JMenuItem m_mntmCut;
public final JMenuItem m_mntmPaste;
public final JMenuItem m_mntmDelete;
public final JMenuItem m_mntmUndo;
public final JMenuItem m_mntmRedo;
public final JMenuItem m_mntmFind;
public final JMenuItem m_mntmReplace;
public JEditMenu(MASSPAEditorMain _mainCtrl, JTabbedPane _editorTabs, ITabController _initEditorTab)
{
super(Labels.s_MENU_EDIT, _editorTabs, _initEditorTab);
// Menu items
m_mntmCopy = new JMenuItem(Labels.s_MENU_EDIT_COPY);
m_mntmCut = new JMenuItem(Labels.s_MENU_EDIT_CUT);
m_mntmPaste = new JMenuItem(Labels.s_MENU_EDIT_PASTE);
m_mntmDelete = new JMenuItem(Labels.s_MENU_EDIT_DELETE);
m_mntmUndo = new JMenuItem(Labels.s_MENU_EDIT_UNDO);
m_mntmRedo = new JMenuItem(Labels.s_MENU_EDIT_REDO);
m_mntmFind = new JMenuItem(Labels.s_MENU_EDIT_FIND);
m_mntmReplace = new JMenuItem(Labels.s_MENU_EDIT_REPLACE);
// Mnemonics and Shortcuts
this.setMnemonic(Shortcuts.s_MENU_EDIT_MNEMONIC);
m_mntmCopy.setMnemonic(Shortcuts.s_MENU_EDIT_COPY_MNEMONIC);
m_mntmCopy.setAccelerator(Shortcuts.s_MENU_EDIT_COPY_ACCELERATOR);
m_mntmCut.setMnemonic(Shortcuts.s_MENU_EDIT_CUT_MNEMONIC);
m_mntmCut.setAccelerator(Shortcuts.s_MENU_EDIT_CUT_ACCELERATOR);
m_mntmPaste.setMnemonic(Shortcuts.s_MENU_EDIT_PASTE_MNEMONIC);
m_mntmPaste.setAccelerator(Shortcuts.s_MENU_EDIT_PASTE_ACCELERATOR);
m_mntmDelete.setMnemonic(Shortcuts.s_MENU_EDIT_DELETE_MNEMONIC);
m_mntmDelete.setAccelerator(Shortcuts.s_MENU_EDIT_DELETE_ACCELERATOR);
m_mntmUndo.setMnemonic(Shortcuts.s_MENU_EDIT_UNDO_MNEMONIC);
m_mntmUndo.setAccelerator(Shortcuts.s_MENU_EDIT_UNDO_ACCELERATOR);
m_mntmRedo.setMnemonic(Shortcuts.s_MENU_EDIT_REDO_MNEMONIC);
m_mntmRedo.setAccelerator(Shortcuts.s_MENU_EDIT_REDO_ACCELERATOR);
m_mntmFind.setMnemonic(Shortcuts.s_MENU_EDIT_FIND_MNEMONIC);
m_mntmFind.setAccelerator(Shortcuts.s_MENU_EDIT_FIND_ACCELERATOR);
m_mntmReplace.setMnemonic(Shortcuts.s_MENU_EDIT_REPLACE_MNEMONIC);
m_mntmReplace.setAccelerator(Shortcuts.s_MENU_EDIT_REPLACE_ACCELERATOR);
// Layout
add(m_mntmCopy);
add(m_mntmCut);
add(m_mntmPaste);
add(m_mntmDelete);
add(new JSeparator());
add(m_mntmUndo);
add(m_mntmRedo);
add(new JSeparator());
add(m_mntmFind);
add(m_mntmReplace);
// Register as Listener
m_mntmCopy.addActionListener(new CopyActionListener());
m_mntmCut.addActionListener(new CutActionListener());
m_mntmPaste.addActionListener(new PasteActionListener());
m_mntmDelete.addActionListener(new DeleteActionListener());
m_mntmUndo.addActionListener(new UndoActionListener());
m_mntmRedo.addActionListener(new RedoActionListener());
m_mntmFind.addActionListener(new FindActionListener());
m_mntmReplace.addActionListener(new ReplaceActionListener());
enableAll(true);
}
//****************************************************************
// Enable/Disable MenuItems
//****************************************************************
protected boolean copyEnabled(ITabController tabCtrl) {m_mntmCopy.setEnabled(tabCtrl instanceof ICopyPasteDeleteHandler); return m_mntmCopy.isEnabled();}
protected boolean cutEnabled(ITabController tabCtrl) {m_mntmCut.setEnabled(tabCtrl instanceof ICopyPasteDeleteHandler); return m_mntmCut.isEnabled();}
protected boolean pasteEnabled(ITabController tabCtrl) {m_mntmPaste.setEnabled(tabCtrl instanceof ICopyPasteDeleteHandler); return m_mntmPaste.isEnabled();}
protected boolean deleteEnabled(ITabController tabCtrl) {m_mntmDelete.setEnabled(tabCtrl instanceof ICopyPasteDeleteHandler); return m_mntmDelete.isEnabled();}
protected boolean undoEnabled(ITabController tabCtrl) {m_mntmUndo.setEnabled(tabCtrl instanceof IUndoRedoHandler && ((IUndoRedoHandler) tabCtrl).canUndo()); return m_mntmUndo.isEnabled();}
protected boolean redoEnabled(ITabController tabCtrl) {m_mntmRedo.setEnabled(tabCtrl instanceof IUndoRedoHandler && ((IUndoRedoHandler) tabCtrl).canRedo()); return m_mntmRedo.isEnabled();}
protected boolean findEnabled(ITabController tabCtrl) {m_mntmFind.setEnabled(tabCtrl instanceof IFindReplaceHandler); return m_mntmFind.isEnabled();}
protected boolean replaceEnabled(ITabController tabCtrl) {m_mntmReplace.setEnabled(tabCtrl instanceof IFindReplaceHandler); return m_mntmReplace.isEnabled();}
@Override
protected void enableAll(boolean _b)
{
m_mntmCopy.setEnabled(_b);
m_mntmCut.setEnabled(_b);
m_mntmPaste.setEnabled(_b);
m_mntmDelete.setEnabled(_b);
m_mntmUndo.setEnabled(_b);
m_mntmRedo.setEnabled(_b);
m_mntmFind.setEnabled(_b);
m_mntmReplace.setEnabled(_b);
}
@Override
protected void enableForTab()
{
if (m_currentEditorCtrl == null) {return;}
// Enable/Disable events based on currently active tab
copyEnabled(m_currentEditorCtrl);
cutEnabled(m_currentEditorCtrl);
pasteEnabled(m_currentEditorCtrl);
deleteEnabled(m_currentEditorCtrl);
undoEnabled(m_currentEditorCtrl);
redoEnabled(m_currentEditorCtrl);
findEnabled(m_currentEditorCtrl);
replaceEnabled(m_currentEditorCtrl);
}
private class CopyActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
// Enable so that we do not miss shortcut events.
// This is necessary since we are not actively listening
// to changes that enable/disable the menuItems
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class CutActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class PasteActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class DeleteActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class UndoActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
if (undoEnabled(m_currentEditorCtrl))
{
((IUndoRedoHandler) m_currentEditorCtrl).undo();
}
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class RedoActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
if (redoEnabled(m_currentEditorCtrl))
{
((IUndoRedoHandler) m_currentEditorCtrl).redo();
}
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class FindActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
private class ReplaceActionListener implements ActionListener
{
//****************************************************************
// Implement the ActionListener interface
//****************************************************************
@Override
public void actionPerformed(ActionEvent _e)
{
((JMenuItem) _e.getSource()).setEnabled(true);
}
}
}
|
package com.wang.mall.front.dto;
import com.wang.mall.model.SmsFlashPromotionSession;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author 王念
* @create 2020-02-20 20:45
*/
public class SmsFlashPromotionWithProduct extends SmsFlashPromotionSession {
private static final long serialVersionUID = -1820157498780868111L;
@Getter
@Setter
private List<SmsFlashPromotionProduct> products;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.acidmanic.commandline.commands;
import com.acidmanic.commandline.commands.context.ExecutionContext;
import com.acidmanic.lightweight.logger.ConsoleLogger;
import com.acidmanic.lightweight.logger.Logger;
/**
*
* @author Mani Moayedi (acidmanic.moayedi@gmail.com)
*/
public class NullCommand implements Command {
private Logger logger = new ConsoleLogger();
private CommandFactory factory = null;
@Override
public void execute(String[] args) {
this.logger.log("No such command.");
}
@Override
public boolean accepts(String name) {
return false;
}
@Override
public boolean hasArguments() {
return false;
}
@Override
public String getArgSplitRegEx() {
return null;
}
@Override
public String getHelpDescription() {
return "";
}
@Override
public void setCreatorFactory(CommandFactory factory) {
this.factory = factory;
}
@Override
public CommandFactory getCreatorFactory() {
return this.factory;
}
@Override
public boolean isVisible() {
return false;
}
@Override
public void setLogger(Logger logger) {
this.logger = logger;
}
@Override
public void setContext(ExecutionContext context) {
}
@Override
public String getName() {
return "Null Command";
}
}
|
package org.upv.satrd.fic2.fe.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
public class Source {
private Integer id;
private String name;
private String description;
private String urlaccess;
private String categorymapping;
private Integer SourceId;
private static org.apache.log4j.Logger log =Logger.getLogger(org.upv.satrd.fic2.fe.db.Source.class);
//The Source object has been inserted in the DDB, and the id is known
public Source(Integer id, String name, String description, String urlaccess, String categorymapping, Integer SourceId ) {
this.id = id;
this.name = name;
this.description = description;
this.urlaccess = urlaccess;
this. categorymapping = categorymapping;
this.SourceId = SourceId;
}
//The Source object has not been inserted in the DDB, and the id is not known
public Source(String name, String description, String urlaccess, String categorymapping, Integer SourceId ) {
this.id = null;
this.name = name;
this.description = description;
this.urlaccess = urlaccess;
this. categorymapping = categorymapping;
this.SourceId = SourceId;
}
//GET METHODS
public Integer getId() {return id;}
public String getName() {return name;}
public String getDescription() {return description;}
public String getUrlaccess() {return urlaccess;}
public String getCategorymapping() {return categorymapping;}
public Integer getAPITypeId() {return SourceId;}
//SET METHODS
public void setId(Integer id){this.id = id;}
public void setName(String name){this.name =name;}
public void setDescription(String description){this.description=description;}
public void setUrlaccess(String urlaccess){this.urlaccess=urlaccess;}
public void setCategorymapping(String categorymapping){this.categorymapping = categorymapping;}
public void setAPITypeId(Integer SourceId){this.SourceId = SourceId;}
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////DB methods/////////////////////////////////////////
public static Source getSourceClassById(Connection con, Integer id){
Source source = null;
Statement stmt;
ResultSet rs;
ArrayList<HashMap<String, Object>> list;
try {
stmt = con.createStatement();
String sql = "SELECT * FROM source WHERE id="+id;
rs = stmt.executeQuery(sql);
Object aux= null;
list = resultSetToArrayList(rs);
if (!list.isEmpty()){
//name field mandatory
String name = (list.get(0)).get("name").toString();
//description field optional
String description = null;
aux = (list.get(0)).get("description");
if (aux!=null) description = aux.toString();
//urlaccess field mandatory
String urlaccess = (list.get(0)).get("urlaccess").toString();
//categorymapping field mandatory
String categorymapping = (list.get(0)).get("categorymapping").toString();
//apitype field mandatory
Integer apitypeId = new Integer((list.get(0)).get("apitypeid").toString());
source = new Source(id, name,description,urlaccess,categorymapping,apitypeId);
}
rs.close();
stmt.close();
} catch ( SQLException e ) {
System.out.println("Error Source.getSourceClassById(): "+e.getMessage());
log.error("Error Source.getSourceClassById(): "+e.getMessage());
}
return source;
}
public static Source getSourceClassByName(Connection con, String name){
Source source = null;
Statement stmt;
ResultSet rs;
ArrayList<HashMap<String, Object>> list;
//For poiproxy.local we search only 'poiproxy';
if (name.toLowerCase().contains("poiproxy")) name = "poiproxy";
try {
stmt = con.createStatement();
String sql = "SELECT * FROM source WHERE name='"+name+"'";
rs = stmt.executeQuery(sql);
Object aux=null;
list = resultSetToArrayList(rs);
if (!list.isEmpty()){
//id field mandatory
Integer id = new Integer((list.get(0)).get("id").toString());
//description field optional
String description = null;
aux = (list.get(0)).get("description");
if (aux!=null) description = aux.toString();
//urlaccess field mandatory
String urlaccess = (list.get(0)).get("urlaccess").toString();
//categorymapping field mandatory
String categorymapping = (list.get(0)).get("categorymapping").toString();
//apitype field mandatory
Integer apitypeId = new Integer((list.get(0)).get("apitypeid").toString());
source = new Source(id, name,description,urlaccess,categorymapping,apitypeId);
}
rs.close();
stmt.close();
} catch ( SQLException e ) {
System.out.println("Error Source.getSourceClassByName() : "+e.getMessage());
log.error("Error Source.getSourceClassByName() : "+e.getMessage());
}
return source;
}
public static Integer saveSource(Connection con, Source source){
Integer id=null;
String sql;
PreparedStatement ps;
try{
sql = "INSERT INTO source (name,description,urlaccess,categorymapping,apitypeid) VALUES (?,?,?,?,?)";
String generatedColumns[] = { "id" };
ps = con.prepareStatement(sql,
generatedColumns);
ps.setString(1,source.getName());
if (source.getDescription() == null) ps.setNull(2, java.sql.Types.VARCHAR); else ps.setString(2,source.getDescription());
ps.setString(3,source.getUrlaccess());
ps.setString(4,source.getCategorymapping());
ps.setInt(5,source.getAPITypeId());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) { id = rs.getInt(1); }
rs.close();
ps.close();
} catch ( SQLException e) {
System.out.println("Error Source.saveSource(): "+e.getMessage());
log.error("Error Source.saveSource(): "+e.getMessage());
}
return id;
}
public static boolean deleteSourceById(Connection con, Integer id){
String sql;
Statement stmt;
try {
//First we need to delete all POILabel that relate to that Source
if (POILabel.deletePOILabelBySourceId(con, id)){
stmt = con.createStatement();
//delete from other tables (ocdsource,sourcecity
sql = "DELETE FROM ocdsource WHERE sourceid="+id+";";
stmt.executeUpdate(sql);
sql = "DELETE FROM sourcecity WHERE sourceid="+id+";";
stmt.executeUpdate(sql);
sql = "DELETE FROM licensesource WHERE sourceid="+id+";";
stmt.executeUpdate(sql);
sql = "DELETE FROM poisource WHERE sourceid="+id+";";
stmt.executeUpdate(sql);
//Finally remove the table entry
sql = "DELETE FROM source WHERE id="+id+";";
stmt.executeUpdate(sql);
stmt.close();
}else return false;
} catch ( SQLException e) {
System.out.println("Error Source.deleteSourceById(): "+e.getMessage());
log.error("Error Source.deleteSourceById(): "+e.getMessage());
return false;
}
return true;
}
public static boolean deleteSourceByName(Connection con, String name){
Source source = Source.getSourceClassByName(con, name);
if (source !=null)
return Source.deleteSourceById(con, source.getId());
else
return false;
}
public static boolean deleteSourceByAPITypeId(Connection con, Integer id){
try {
//delete dependencies with other tables
//Get all Sources, retrieve their id and delete them
ArrayList<Source> source_array = getSourceListByAPITypeId(con,id);
for (int k=0;k<source_array.size();k++){
Source source = source_array.get(k);
deleteSourceById(con,source.getId());
}
} catch ( Exception e) {
System.out.println("Error Source.deleteSourceById(): "+e.getMessage());
log.error("Error Source.deleteSourceById(): "+e.getMessage());
return false;
}
return true;
}
public static boolean updateSource(Connection con, Source source){
String sql;
PreparedStatement ps;
try{
sql = "UPDATE source SET name=?, description=?, urlaccess=?, categorymapping=?, apitype=? WHERE id="+source.getId();
ps = con.prepareStatement(sql);
ps.setString(1,source.getName());
if (source.getDescription() == null) ps.setNull(2, java.sql.Types.VARCHAR); else ps.setString(2,source.getDescription());
ps.setString(3,source.getUrlaccess());
ps.setString(4,source.getCategorymapping());
ps.setInt(5,source.getAPITypeId());
ps.executeUpdate();
ps.close();
} catch ( SQLException e) {
System.out.println("Error Source.updateSource(): "+e.getMessage());
log.error("Error Source.updateSource(): "+e.getMessage());
return false;
}
return true;
}
public static ArrayList<Source> getSourceList (Connection con){
ArrayList<Source> source_array = new ArrayList<Source>();
String sql;
Statement stmt;
ResultSet rs;
ArrayList<HashMap<String, Object>> list;
try {
stmt = con.createStatement();
sql = "SELECT * FROM source ORDER BY name";
rs = stmt.executeQuery(sql);
Object aux=null;
list = resultSetToArrayList(rs);
if (!list.isEmpty()){
for (int k=0;k<list.size();k++){
//id field mandatory
Integer id = new Integer((list.get(k)).get("id").toString());
//name field mandatory
String name = (list.get(k)).get("name").toString();
//description field optional
String description = null;
aux = (list.get(k)).get("description");
if (aux!=null) description = aux.toString();
//urlaccess field mandatory
String urlaccess = (list.get(k)).get("urlaccess").toString();
//categorymapping field mandatory
String categorymapping = (list.get(k)).get("categorymapping").toString();
//apitype field mandatory
Integer apitypeId = new Integer((list.get(k)).get("apitypeid").toString());
Source source = new Source(id, name,description,urlaccess,categorymapping,apitypeId);
source_array.add(source);
}
}
rs.close();
stmt.close();
} catch ( Exception e ) {
System.out.println("Error Source.getSourceList(): "+e.getMessage());
log.error("Error Source.getSourceList(): "+e.getMessage());
}
return source_array;
}
public static ArrayList<Source> getSourceListByAPITypeId (Connection con, Integer apitypeId){
ArrayList<Source> source_array = new ArrayList<Source>();
String sql;
Statement stmt;
ResultSet rs;
ArrayList<HashMap<String, Object>> list;
try {
stmt = con.createStatement();
sql = "SELECT * FROM source WHERE apitypeid="+apitypeId;
rs = stmt.executeQuery(sql);
Object aux=null;
list = resultSetToArrayList(rs);
if (!list.isEmpty()){
for (int k=0;k<list.size();k++){
//id field mandatory
Integer id = new Integer((list.get(k)).get("id").toString());
//name field mandatory
String name = (list.get(k)).get("name").toString();
//description field optional
String description = null;
aux = (list.get(k)).get("description");
if (aux!=null) description = aux.toString();
//urlaccess field mandatory
String urlaccess = (list.get(k)).get("urlaccess").toString();
//categorymapping field mandatory
String categorymapping = (list.get(k)).get("categorymapping").toString();
Source source = new Source(id, name,description,urlaccess,categorymapping,apitypeId);
source_array.add(source);
}
}
rs.close();
stmt.close();
} catch ( Exception e ) {
System.out.println("Error Source.getSourceList(): "+e.getMessage());
log.error("Error Source.getSourceList(): "+e.getMessage());
}
return source_array;
}
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Utility method///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<HashMap<String, Object>> resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList<HashMap<String, Object>> results = new ArrayList<HashMap<String, Object>>();
while (rs.next()) {
HashMap<String, Object> row = new HashMap<String, Object>();
for(int i=1; i<=columns; i++){
row.put(md.getColumnName(i).toLowerCase().toLowerCase(),rs.getObject(i));
}
results.add(row);
}
return results;
}
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////testing method///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
public static void testSource(Connection con) {
System.out.println("****************************************************************************************");
System.out.println("Source test. Creating, inserting,selecting and deleting an Source object from DB");
log.info("****************************************************************************************");
log.info("Source test. Creating, inserting,selecting and deleting an Source object from DB");
String name = "some_name";
String description = "some_description";
String urlaccess = "some_urlaccess";
String categorymapping = "some_categorymapping";
//We need to create first an APIType
String api_name = "some_apiname";
String api_description = "some_apidescription";
String apirules = "some_apirules";
APIType apitype = new APIType(api_name,api_description,apirules);
Integer apitypeId = APIType.saveAPIType(con, apitype);
Source source = new Source(name,description,urlaccess,categorymapping,apitypeId);
System.out.println("Creating Source class...... OK");
log.info("Creating Source class......OK");
Integer id = Source.saveSource(con, source);
if (id==null){
System.out.println("Saving Source class...... Error ");
log.info("Saving Source class...... Error ");
}else{
System.out.println("Saving Source class...... OK ");
log.info("Saving Source class...... OK ");
Source Source2 = Source.getSourceClassById(con, id);
if (Source2==null){
System.out.println("Getting Source class by ID...... Error ");
log.info("Getting Source class by ID...... Error ");
}else{
System.out.println("Getting Source class by ID...... OK ");
log.info("Getting Source class by ID...... OK ");
Source2 = Source.getSourceClassByName(con, name);
if (Source2 == null){
System.out.println("Getting Source class by Name...... Error ");
log.info("Getting Source class by Name...... Error ");
}else{
System.out.println("Getting Source class by Name...... OK ");
log.info("Getting Source class by Name...... OK ");
if (!Source.deleteSourceById(con, id)){
System.out.println("Deleting Source class by ID ...... Error ");
log.info("Deleting Source class by ID ...... Error ");
}else{
System.out.println("Deleting Source class by ID ...... OK ");
log.info("Deleting Source class by ID ...... OK ");
id = Source.saveSource(con, source);
if (id!=null){
if (!Source.deleteSourceByName(con, name)){
System.out.println("Deleting Source class by Name ...... Error ");
log.info("Deleting Source class by Name ...... Error ");
}else{
System.out.println("Deleting Source class by Name ...... OK ");
log.info("Deleting Source class by Name ...... OK ");
System.out.println("All tests passed OK");
log.info("All tests passed OK");
}
}
}
}
}
}
System.out.println("****************************************************************************************");
log.info("****************************************************************************************");
}
}
|
/**
* Copyright 2017 Confluent 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 io.confluent.ksql.parser.tree;
public final class NodeLocation {
private final int line;
private final int charPositionInLine;
public NodeLocation(final int line, final int charPositionInLine) {
this.line = line;
this.charPositionInLine = charPositionInLine;
}
public int getLineNumber() {
return line;
}
public int getColumnNumber() {
return charPositionInLine + 1;
}
@Override
public String toString() {
return String.format(" Line: %d, Col: %d", line, charPositionInLine + 1);
}
}
|
package com.example.mecolweather;
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("com.example.mecolweather", appContext.getPackageName());
}
}
|
package com.hourlyweather.forecast;
import java.io.Serializable;
import java.util.HashMap;
public class ForecastHour implements Serializable {
private static final long serialVersionUID = 1L;
private Double temp;
private Double precipitation, windSpeed;
private String symbol;
private Boolean isSunUp;
private static final HashMap<String, Integer> symbolCodes;
static {
symbolCodes = new HashMap<String, Integer>();
symbolCodes.put("Sun", 1);
symbolCodes.put("LightCloud", 2);
symbolCodes.put("PartlyCloud", 3);
symbolCodes.put("Cloud", 4);
symbolCodes.put("LightRainSun", 5);
symbolCodes.put("LightRainThunderSun", 6);
symbolCodes.put("SleetSun", 7);
symbolCodes.put("SnowSun", 8);
symbolCodes.put("LightRain", 9);
symbolCodes.put("Rain", 10);
symbolCodes.put("RainThunder", 11);
symbolCodes.put("Sleet", 12);
symbolCodes.put("Snow", 13);
symbolCodes.put("SnowThunder", 14);
symbolCodes.put("Fog", 15);
}
public ForecastHour() {
precipitation = null;
temp = null;
symbol = null;
}
public ForecastHour(ForecastHour existing, ForecastHour updated) {
this.symbol = updated.getSymbol() == null ? existing.getSymbol()
: updated.getSymbol();
this.temp = updated.getTemp() == null ? existing.getTemp() : updated
.getTemp();
this.precipitation = updated.getPrecipitation() == null ? existing
.getPrecipitation() : updated.getPrecipitation();
this.windSpeed = updated.getWindSpeed() == null ? existing
.getWindSpeed() : updated.getWindSpeed();
this.isSunUp = updated.isSunUp() == null ? existing.isSunUp() : updated
.isSunUp();
}
public Double getTemp() {
return temp;
}
public void setTemp(String temp) {
try {
this.temp = Double.parseDouble(temp);
} catch (Exception e) {
// nothing we can do now, the api may have changed
}
}
/*
* 1 SUN 2 LIGHTCLOUD 3 PARTLYCLOUD 4 CLOUD 5 LIGHTRAINSUN 6
* LIGHTRAINTHUNDERSUN 7 SLEETSUN 8 SNOWSUN 9 LIGHTRAIN 10 RAIN 11
* RAINTHUNDER 12 SLEET 13 SNOW 14 SNOWTHUNDER 15 FOG
*/
public void setTemp(Double temp) {
this.temp = temp;
}
public String getSymbol() {
return symbol;
}
public int getSymbolCode() {
Integer code = symbolCodes.get(symbol);
if(code == null) {
String s = symbol.toLowerCase();
if(s.contains("sleet"))
code = 12;
else if(s.contains("drizzle") || s.contains("rain"))
code = 10;
else if(s.contains("snow"))
code = 13;
}
return code;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setPrecipitation(Double precipitation) {
this.precipitation = precipitation;
}
public Double getPrecipitation() {
return precipitation;
}
public void setWindSpeed(Double windSpeed) {
this.windSpeed = windSpeed;
}
public Double getWindSpeed() {
return windSpeed;
}
public void setSunUp(Boolean isSunUp) {
this.isSunUp = isSunUp;
}
public Boolean isSunUp() {
return isSunUp;
}
/**
* combines the current forecast hour with the passed in parameter. The
* passed in objects parameters take presidence
*
* @param forecastHour
*/
public void combine(ForecastHour forecastHour) {
if (forecastHour == null)
return;
if (forecastHour.getTemp() != null)
temp = forecastHour.getTemp();
if (forecastHour.getSymbol() != null)
symbol = forecastHour.getSymbol();
if (forecastHour.getPrecipitation() != null)
precipitation = forecastHour.getPrecipitation();
if (forecastHour.isSunUp() != null)
isSunUp = forecastHour.isSunUp();
}
/**
* fills in any unpopulated fields with the passed in forecastHours values
*
* @param forecastHour
*/
public void backFill(ForecastHour forecastHour) {
if (forecastHour == null)
return;
if (temp == null)
temp = forecastHour.getTemp();
if (symbol == null)
symbol = forecastHour.getSymbol();
if (precipitation == null)
precipitation = forecastHour.getPrecipitation();
if (windSpeed == null)
windSpeed = forecastHour.getWindSpeed();
if (isSunUp == null)
isSunUp = forecastHour.isSunUp();
}
public boolean complete() {
if (temp != null && symbol != null && isSunUp != null
&& precipitation != null && windSpeed != null)
return true;
return false;
}
}
|
package misc.utils;
import java.util.Stack;
public final class ExpressionEvaluator {
private ExpressionEvaluator() {
}
public static int evaluate(String expression) {
char[] tokens = expression.toCharArray();
Stack<Integer> values = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ')
continue;
if (tokens[i] >= '0' && tokens[i] <= '9') {
StringBuilder stringBuffer = new StringBuilder();
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
stringBuffer.append(tokens[i++]);
i--;
values.push(Integer.parseInt(stringBuffer.toString()));
} else if (tokens[i] == '(')
operators.push(tokens[i]);
else if (tokens[i] == ')') {
while (operators.peek() != '(')
values.push(applyOperation(operators.pop(), values.pop(), values.pop()));
operators.pop();
} else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/') {
while (!operators.empty() && hasPrecedence(tokens[i], operators.peek()))
values.push(applyOperation(operators.pop(), values.pop(), values.pop()));
operators.push(tokens[i]);
}
}
while (!operators.empty())
values.push(applyOperation(operators.pop(), values.pop(), values.pop()));
return values.pop();
}
private static boolean hasPrecedence(char firstOperation, char secondOperation) {
if (secondOperation == '(' || secondOperation == ')')
return false;
return (firstOperation != '*' && firstOperation != '/') || (secondOperation != '+' && secondOperation != '-');
}
private static int applyOperation(char operation, int secondNum, int firstNum) {
switch (operation) {
case '+':
return firstNum + secondNum;
case '-':
return firstNum - secondNum;
case '*':
return firstNum * secondNum;
case '/':
if (secondNum == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return firstNum / secondNum;
}
return 0;
}
}
|
package com.niluogege.server.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.niluogege.server.pojo.PoliticsStatus;
/**
* <p>
* 服务类
* </p>
*
* @author niluogege
* @since 2021-10-29
*/
public interface IPoliticsStatusService extends IService<PoliticsStatus> {
}
|
package info.archinnov.achilles.table;
import java.util.List;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.TableMetadata;
import com.google.common.collect.ComparisonChain;
public class CQLColumnMetaDataComparator {
public boolean isEqual(ColumnMetadata source, ColumnMetadata target) {
boolean isEqual = false;
final String sourceName = source.getName();
final TableMetadata sourceTable = source.getTable();
final DataType sourceType = source.getType();
final Class<?> sourceClass = sourceType.asJavaClass();
final List<DataType> sourceTypeParams = sourceType.getTypeArguments();
final String targetName = target.getName();
final TableMetadata targetTable = target.getTable();
final DataType targetType = target.getType();
final Class<?> targetClass = targetType.asJavaClass();
final List<DataType> targetTypeParams = targetType.getTypeArguments();
final boolean isPartiallyEqual = ComparisonChain.start()
.compare(sourceName, targetName)
.compare(sourceTable.getName(), targetTable.getName())
.compare(sourceType.getName(), targetType.getName())
.compareFalseFirst(sourceType.isCollection(), targetType.isCollection())
.result() == 0;
final boolean isSameClass = sourceClass.equals(targetClass);
final boolean bothHaveTypeParameters = (sourceTypeParams != null && targetTypeParams != null) || (sourceTypeParams == null && targetTypeParams == null);
isEqual = isPartiallyEqual && isSameClass && bothHaveTypeParameters;
if(isEqual && sourceTypeParams != null) {
isEqual = (sourceTypeParams.size() == targetTypeParams.size());
if(isEqual) {
for(int i=0; i<sourceTypeParams.size(); i++) {
final DataType sourceParamType = sourceTypeParams.get(i);
final DataType targetParamType = targetTypeParams.get(i);
final boolean sameParamType = ComparisonChain.start()
.compare(sourceParamType.getName(),targetParamType.getName())
.result() == 0;
if(!sameParamType) {
return false;
}
}
}
}
return isEqual;
}
}
|
package com.x1ma.spawnerupgrade.common.items;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class ItemBasic extends Item
{
public ItemBasic(String name)
{
this.setUnlocalizedName(name);
this.setRegistryName(name);
this.setCreativeTab(CreativeTabs.MATERIALS);
}
}
|
/*
*
* 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 com.alibaba.dubbo.samples.stub.impl;
import com.alibaba.dubbo.samples.stub.api.DemoService;
public class DemoServiceStub implements DemoService{
private final DemoService demoService;
public DemoServiceStub(DemoService demoService) {
this.demoService = demoService;
}
public String sayHello(String name) {
//client check code goes here
System.out.println("stub sayHello");
try {
return demoService.sayHello(name);
} catch (Exception e) {
//handle Exception
return null;
}
}
}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.customize;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.CreateLauncherScriptAction;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import java.awt.*;
public class CustomizeLauncherScriptStep extends AbstractCustomizeWizardStep {
public static boolean isAvailable() {
return System.getProperty("idea.skip.launcher.script.step") == null && CreateLauncherScriptAction.isAvailable();
}
private final JCheckBox myCreateScriptCheckBox = new JCheckBox(ActionsBundle.message("action.CreateLauncherScript.description"));
private final JTextField myScriptPathTextField = new JTextField();
public CustomizeLauncherScriptStep() {
setLayout(new BorderLayout());
myCreateScriptCheckBox.setOpaque(false);
myCreateScriptCheckBox.setSelected(false);
myCreateScriptCheckBox.addChangeListener(e -> myScriptPathTextField.setEnabled(myCreateScriptCheckBox.isSelected()));
myScriptPathTextField.setEnabled(false);
myScriptPathTextField.setText(CreateLauncherScriptAction.defaultScriptPath());
JPanel content = new JPanel(createSmallBorderLayout());
content.setBorder(createSmallEmptyBorder());
JPanel controls = new JPanel(new GridBagLayout());
controls.setOpaque(false);
GridBag gbc = new GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultFill(GridBagConstraints.HORIZONTAL).setDefaultWeightX(1);
controls.add(myCreateScriptCheckBox, gbc.nextLine());
gbc.nextLine();
gbc.insets.top = UIUtil.PANEL_REGULAR_INSETS.top;
gbc.insets.left = UIUtil.PANEL_REGULAR_INSETS.left;
controls.add(new JLabel(IdeBundle.message("label.please.specify.the.path.where.the.script.should.be.created")), gbc);
controls.add(myScriptPathTextField, gbc.nextLine());
content.add(controls, BorderLayout.NORTH);
add(content, BorderLayout.CENTER);
}
@Override
public boolean beforeOkAction() {
if (myCreateScriptCheckBox.isSelected()) {
CustomizeIDEWizardInteractions.INSTANCE.record(CustomizeIDEWizardInteractionType.LauncherScriptCreated);
try {
CreateLauncherScriptAction.createLauncherScript(myScriptPathTextField.getText());
}
catch (Exception e) {
Messages.showErrorDialog(ExceptionUtil.getNonEmptyMessage(e, "Internal error"),
IdeBundle.message("dialog.title.launcher.script.creation.failed"));
return false;
}
}
return true;
}
@Override
protected String getTitle() {
return IdeBundle.message("step.title.launcher.script");
}
@Override
protected String getHTMLHeader() {
return IdeBundle.message("label.create.launcher.script");
}
@Override
protected String getHTMLFooter() {
return IdeBundle.message("label.launcher.script.can.be.created.later.via.tools.create.command.line.launcher");
}
}
|
package com.example.tuanpd.myapplication;
import java.util.Timer;
import java.util.TimerTask;
public class LocationTimer {
private Timer mTimer;
private TimerTask mTask = new TimerTask() {
@Override
public void run() {
//
}
};
public void cancel() {
if (mTimer != null) {
mTimer.cancel();
}
}
public void start(long intervalTime) {
if (mTimer == null) {
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(mTask, 0, intervalTime);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.ClassRule;
import org.junit.experimental.categories.Category;
@Category({ MediumTests.class, ClientTests.class })
public class TestSnapshotWithAclAsyncAdmin extends SnapshotWithAclTestBase {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestSnapshotWithAclAsyncAdmin.class);
@Override
protected void snapshot(String snapshotName, TableName tableName) throws Exception {
try (AsyncConnection conn =
ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get()) {
conn.getAdmin().snapshot(snapshotName, tableName).get();
}
}
@Override
protected void cloneSnapshot(String snapshotName, TableName tableName, boolean restoreAcl)
throws Exception {
try (AsyncConnection conn =
ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get()) {
conn.getAdmin().cloneSnapshot(snapshotName, tableName, restoreAcl).get();
}
}
@Override
protected void restoreSnapshot(String snapshotName, boolean restoreAcl) throws Exception {
try (AsyncConnection conn =
ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get()) {
conn.getAdmin().restoreSnapshot(snapshotName, false, restoreAcl).get();
}
}
}
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.api.server.cors.v1.function;
import org.wso2.carbon.identity.api.server.cors.v1.model.CORSApplicationObject;
import org.wso2.carbon.identity.cors.mgt.core.model.CORSApplication;
import java.util.function.Function;
/**
* Converts a CORSOrigin instance to a CORSOriginGetObject instance.
*/
public class CORSApplicationToCORSApplicationObject implements Function<CORSApplication, CORSApplicationObject> {
@Override
public CORSApplicationObject apply(CORSApplication corsApplication) {
CORSApplicationObject corsApplicationObject = new CORSApplicationObject();
corsApplicationObject.setId(corsApplication.getId());
corsApplicationObject.setName(corsApplication.getName());
return corsApplicationObject;
}
}
|
/*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import java.util.ArrayList;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* DescribeSecurityGroupsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeSecurityGroupsResultStaxUnmarshaller implements Unmarshaller<DescribeSecurityGroupsResult, StaxUnmarshallerContext> {
public DescribeSecurityGroupsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
DescribeSecurityGroupsResult describeSecurityGroupsResult = new DescribeSecurityGroupsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return describeSecurityGroupsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("securityGroupInfo", targetDepth)) {
describeSecurityGroupsResult.withSecurityGroups(new ArrayList<SecurityGroup>());
continue;
}
if (context.testExpression("securityGroupInfo/item", targetDepth)) {
describeSecurityGroupsResult.withSecurityGroups(SecurityGroupStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("nextToken", targetDepth)) {
describeSecurityGroupsResult.setNextToken(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return describeSecurityGroupsResult;
}
}
}
}
private static DescribeSecurityGroupsResultStaxUnmarshaller instance;
public static DescribeSecurityGroupsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeSecurityGroupsResultStaxUnmarshaller();
return instance;
}
}
|
package com.google.ads.googleads.v6.services;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* Service to fetch feed placeholder views.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/ads/googleads/v6/services/feed_placeholder_view_service.proto")
public final class FeedPlaceholderViewServiceGrpc {
private FeedPlaceholderViewServiceGrpc() {}
public static final String SERVICE_NAME = "google.ads.googleads.v6.services.FeedPlaceholderViewService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest,
com.google.ads.googleads.v6.resources.FeedPlaceholderView> getGetFeedPlaceholderViewMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetFeedPlaceholderView",
requestType = com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest.class,
responseType = com.google.ads.googleads.v6.resources.FeedPlaceholderView.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest,
com.google.ads.googleads.v6.resources.FeedPlaceholderView> getGetFeedPlaceholderViewMethod() {
io.grpc.MethodDescriptor<com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest, com.google.ads.googleads.v6.resources.FeedPlaceholderView> getGetFeedPlaceholderViewMethod;
if ((getGetFeedPlaceholderViewMethod = FeedPlaceholderViewServiceGrpc.getGetFeedPlaceholderViewMethod) == null) {
synchronized (FeedPlaceholderViewServiceGrpc.class) {
if ((getGetFeedPlaceholderViewMethod = FeedPlaceholderViewServiceGrpc.getGetFeedPlaceholderViewMethod) == null) {
FeedPlaceholderViewServiceGrpc.getGetFeedPlaceholderViewMethod = getGetFeedPlaceholderViewMethod =
io.grpc.MethodDescriptor.<com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest, com.google.ads.googleads.v6.resources.FeedPlaceholderView>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetFeedPlaceholderView"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.google.ads.googleads.v6.resources.FeedPlaceholderView.getDefaultInstance()))
.setSchemaDescriptor(new FeedPlaceholderViewServiceMethodDescriptorSupplier("GetFeedPlaceholderView"))
.build();
}
}
}
return getGetFeedPlaceholderViewMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static FeedPlaceholderViewServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceStub>() {
@java.lang.Override
public FeedPlaceholderViewServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceStub(channel, callOptions);
}
};
return FeedPlaceholderViewServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static FeedPlaceholderViewServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceBlockingStub>() {
@java.lang.Override
public FeedPlaceholderViewServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceBlockingStub(channel, callOptions);
}
};
return FeedPlaceholderViewServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static FeedPlaceholderViewServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<FeedPlaceholderViewServiceFutureStub>() {
@java.lang.Override
public FeedPlaceholderViewServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceFutureStub(channel, callOptions);
}
};
return FeedPlaceholderViewServiceFutureStub.newStub(factory, channel);
}
/**
* <pre>
* Service to fetch feed placeholder views.
* </pre>
*/
public static abstract class FeedPlaceholderViewServiceImplBase implements io.grpc.BindableService {
/**
* <pre>
* Returns the requested feed placeholder view in full detail.
* </pre>
*/
public void getFeedPlaceholderView(com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest request,
io.grpc.stub.StreamObserver<com.google.ads.googleads.v6.resources.FeedPlaceholderView> responseObserver) {
asyncUnimplementedUnaryCall(getGetFeedPlaceholderViewMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getGetFeedPlaceholderViewMethod(),
asyncUnaryCall(
new MethodHandlers<
com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest,
com.google.ads.googleads.v6.resources.FeedPlaceholderView>(
this, METHODID_GET_FEED_PLACEHOLDER_VIEW)))
.build();
}
}
/**
* <pre>
* Service to fetch feed placeholder views.
* </pre>
*/
public static final class FeedPlaceholderViewServiceStub extends io.grpc.stub.AbstractAsyncStub<FeedPlaceholderViewServiceStub> {
private FeedPlaceholderViewServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected FeedPlaceholderViewServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceStub(channel, callOptions);
}
/**
* <pre>
* Returns the requested feed placeholder view in full detail.
* </pre>
*/
public void getFeedPlaceholderView(com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest request,
io.grpc.stub.StreamObserver<com.google.ads.googleads.v6.resources.FeedPlaceholderView> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getGetFeedPlaceholderViewMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* Service to fetch feed placeholder views.
* </pre>
*/
public static final class FeedPlaceholderViewServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<FeedPlaceholderViewServiceBlockingStub> {
private FeedPlaceholderViewServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected FeedPlaceholderViewServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* Returns the requested feed placeholder view in full detail.
* </pre>
*/
public com.google.ads.googleads.v6.resources.FeedPlaceholderView getFeedPlaceholderView(com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest request) {
return blockingUnaryCall(
getChannel(), getGetFeedPlaceholderViewMethod(), getCallOptions(), request);
}
}
/**
* <pre>
* Service to fetch feed placeholder views.
* </pre>
*/
public static final class FeedPlaceholderViewServiceFutureStub extends io.grpc.stub.AbstractFutureStub<FeedPlaceholderViewServiceFutureStub> {
private FeedPlaceholderViewServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected FeedPlaceholderViewServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new FeedPlaceholderViewServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* Returns the requested feed placeholder view in full detail.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v6.resources.FeedPlaceholderView> getFeedPlaceholderView(
com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest request) {
return futureUnaryCall(
getChannel().newCall(getGetFeedPlaceholderViewMethod(), getCallOptions()), request);
}
}
private static final int METHODID_GET_FEED_PLACEHOLDER_VIEW = 0;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final FeedPlaceholderViewServiceImplBase serviceImpl;
private final int methodId;
MethodHandlers(FeedPlaceholderViewServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_GET_FEED_PLACEHOLDER_VIEW:
serviceImpl.getFeedPlaceholderView((com.google.ads.googleads.v6.services.GetFeedPlaceholderViewRequest) request,
(io.grpc.stub.StreamObserver<com.google.ads.googleads.v6.resources.FeedPlaceholderView>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class FeedPlaceholderViewServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
FeedPlaceholderViewServiceBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.ads.googleads.v6.services.FeedPlaceholderViewServiceProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("FeedPlaceholderViewService");
}
}
private static final class FeedPlaceholderViewServiceFileDescriptorSupplier
extends FeedPlaceholderViewServiceBaseDescriptorSupplier {
FeedPlaceholderViewServiceFileDescriptorSupplier() {}
}
private static final class FeedPlaceholderViewServiceMethodDescriptorSupplier
extends FeedPlaceholderViewServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
FeedPlaceholderViewServiceMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (FeedPlaceholderViewServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new FeedPlaceholderViewServiceFileDescriptorSupplier())
.addMethod(getGetFeedPlaceholderViewMethod())
.build();
}
}
}
return result;
}
}
|
/**
* 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.pinot.client;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Reimplementation of BrokerResponse from pinot-common, so that pinot-api does not depend on pinot-common.
*/
class BrokerResponse {
private JsonNode _aggregationResults;
private JsonNode _selectionResults;
private JsonNode _exceptions;
private BrokerResponse() {
}
private BrokerResponse(JsonNode brokerResponse) {
_aggregationResults = brokerResponse.get("aggregationResults");
_exceptions = brokerResponse.get("exceptions");
_selectionResults = brokerResponse.get("selectionResults");
}
boolean hasExceptions() {
return _exceptions != null && _exceptions.size() != 0;
}
JsonNode getExceptions() {
return _exceptions;
}
JsonNode getAggregationResults() {
return _aggregationResults;
}
JsonNode getSelectionResults() {
return _selectionResults;
}
int getAggregationResultsSize() {
if (_aggregationResults == null) {
return 0;
} else {
return _aggregationResults.size();
}
}
static BrokerResponse fromJson(JsonNode json) {
return new BrokerResponse(json);
}
static BrokerResponse empty() {
return new BrokerResponse();
}
}
|
/**
*
*/
package com.github.tosdan.utils.varie;
import org.apache.commons.io.FilenameUtils;
/**
*
* @author Daniele
*
*/
public class FilenameTools {
/**
* Restituisce il nome del file con una stringa casuale alfanumerica di 9 caratteri inserita dopo il nome
* file passato come parametro.
* Es: <b>helloworld.txt</b> => <b>helloworld_abcd1234z.txt</b>
* @param filename
* @return
*/
public static String getRandomizedFilename(String filename) {
String filenameUnivico = null;
String estensione = FilenameUtils.getExtension(filename);
String randomString = RandUtils.getRandomString(9); // 1 collisione ogni 10.000.000
filenameUnivico = FilenameUtils.getBaseName(filename) + "_" + randomString +"."+ estensione;
return filenameUnivico;
}
}
|
package com.hudson.donglingmusic.service.playState;
import com.hudson.donglingmusic.R;
import com.hudson.donglingmusic.service.playState.shuffle.ShuffleState;
/**
* Created by Hudson on 2020/3/13.
*/
public class LoopListState extends BaseState {
public LoopListState() {
super(R.drawable.play_mode_looper_list,R.string.play_mode_loop_list);
}
@Override
protected int pre(int curIndex) {
if(curIndex > 0){
return curIndex - 1;
}else{
return mSize - 1;
}
}
@Override
protected int next(int curIndex) {
if(curIndex < mSize - 1){
return curIndex + 1;
}else{
return 0;
}
}
@Override
protected IState createNextState() {
return new ShuffleState();
}
}
|
package com.dreamwagon.vclouds;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
|
/*
* Copyright (c) 2005, 2013, 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 java.sql;
/**
* Interface for JDBC classes which provide the ability to retrieve the delegate instance when the instance
* in question is in fact a proxy class.
* <p>
* The wrapper pattern is employed by many JDBC driver implementations to provide extensions beyond
* the traditional JDBC API that are specific to a data source. Developers may wish to gain access to
* these resources that are wrapped (the delegates) as proxy class instances representing the
* the actual resources. This interface describes a standard mechanism to access
* these wrapped resources
* represented by their proxy, to permit direct access to the resource delegates.
*
* @since 1.6
*/
public interface Wrapper {
/**
* Returns an object that implements the given interface to allow access to
* non-standard methods, or standard methods not exposed by the proxy.
* <p>
* If the receiver implements the interface then the result is the receiver
* or a proxy for the receiver. If the receiver is a wrapper
* and the wrapped object implements the interface then the result is the
* wrapped object or a proxy for the wrapped object. Otherwise return the
* the result of calling <code>unwrap</code> recursively on the wrapped object
* or a proxy for that result. If the receiver is not a
* wrapper and does not implement the interface, then an <code>SQLException</code> is thrown.
*
* @param <T> the type of the class modeled by this Class object
* @param iface A Class defining an interface that the result must implement.
* @return an object that implements the interface. May be a proxy for the actual implementing object.
* @throws java.sql.SQLException If no object found that implements the interface
* @since 1.6
*/
<T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException;
/**
* Returns true if this either implements the interface argument or is directly or indirectly a wrapper
* for an object that does. Returns false otherwise. If this implements the interface then return true,
* else if this is a wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped
* object. If this does not implement the interface and is not a wrapper, return false.
* This method should be implemented as a low-cost operation compared to <code>unwrap</code> so that
* callers can use this method to avoid expensive <code>unwrap</code> calls that may fail. If this method
* returns true then calling <code>unwrap</code> with the same argument should succeed.
*
* @param iface a Class defining an interface.
* @return true if this implements the interface or directly or indirectly wraps an object that does.
* @throws java.sql.SQLException if an error occurs while determining whether this is a wrapper
* for an object with the given interface.
* @since 1.6
*/
boolean isWrapperFor(java.lang.Class<?> iface) throws java.sql.SQLException;
}
|
/*
* @(#)ColorTableCellEditor.java
* CubeTwister. Copyright © 2020 Werner Randelshofer, Switzerland. MIT License.
*/
package ch.randelshofer.gui.table;
import ch.randelshofer.gui.Colors;
import ch.randelshofer.gui.PolygonIcon;
import org.jhotdraw.annotation.Nonnull;
import org.jhotdraw.annotation.Nullable;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* ColorTableCellEditor..
*/
public class ColorTableCellEditor extends DefaultCellEditor {
private final static long serialVersionUID = 1L;
private PolygonIcon icon;
@Nullable Color currentColor = null;
public ColorTableCellEditor() {
super(new JCheckBox()); //Unfortunately, the constructor
//expects a check box, combo box,
//or text field.
icon = new PolygonIcon(
new Polygon(
new int[] {0, 24, 24, 0},
new int[] {0, 0, 12, 12},
4
),
new Dimension(25, 13)
);
final JButton button = new JButton(icon);
button.setBorderPainted(false);
button.setMargin(new Insets(0,1,0,0));
button.setHorizontalAlignment(SwingConstants.LEFT);
editorComponent = button;
//Set up the dialog that the button brings up.
final JColorChooser colorChooser = new JColorChooser();
ActionListener okListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color c = colorChooser.getColor();
if (c != null) {
ColorTableCellEditor.this.currentColor = c;
}
}
};
final JDialog dialog = JColorChooser.createDialog(button,
"Pick a Color",
true,
colorChooser,
okListener,
null); //XXXDoublecheck this is OK
//Here's the code that brings up the dialog.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorChooser.setColor(ColorTableCellEditor.this.currentColor);
//Without the following line, the dialog comes up
//in the middle of the screen.
dialog.setLocationRelativeTo(button);
dialog.setVisible(true);
//Must do this so that editing stops when appropriate.
fireEditingStopped();
}
});
setClickCountToStart(1); //This is usually 1 or 2.
}
/**
* Creates new ColorTableCellEditor
*/
public ColorTableCellEditor(@Nonnull JButton b) {
super(new JCheckBox()); //Unfortunately, the constructor
//expects a check box, combo box,
//or text field.
editorComponent = b;
setClickCountToStart(1); //This is usually 1 or 2.
//Must do this so that editing stops when appropriate.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
@Nullable
public Object getCellEditorValue() {
return currentColor;
}
public Component getTableCellEditorComponent(@Nonnull JTable table,
Object value,
boolean isSelected,
int row,
int column) {
JButton button = (JButton) editorComponent;
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
currentColor = (Color) value;
icon.setFillColor(currentColor);
if (currentColor == null) {
icon.setForeground(Color.black);
button.setText("---");
} else {
icon.setForeground(Colors.shadow(currentColor, 38));
button.setText(currentColor.getRed() + "r "+ currentColor.getGreen() + "g " + currentColor.getBlue()+"b");
}
return editorComponent;
}
}
|
package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.open.app.silan.luckyeight.query response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class AlipayOpenAppSilanLuckyeightQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 6384291374726616859L;
}
|
/*
* 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.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.search.fetch.subphase;
import org.opensearch.Version;
import org.opensearch.common.Nullable;
import org.opensearch.common.ParseField;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.io.stream.StreamOutput;
import org.opensearch.common.io.stream.Writeable;
import org.opensearch.common.xcontent.ConstructingObjectParser;
import org.opensearch.common.xcontent.ToXContentObject;
import org.opensearch.common.xcontent.XContent;
import org.opensearch.common.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
/**
* Wrapper around a field name and the format that should be used to
* display values of this field.
*/
public final class FieldAndFormat implements Writeable, ToXContentObject {
private static final ParseField FIELD_FIELD = new ParseField("field");
private static final ParseField FORMAT_FIELD = new ParseField("format");
private static final ConstructingObjectParser<FieldAndFormat, Void> PARSER = new ConstructingObjectParser<>("docvalues_field",
a -> new FieldAndFormat((String) a[0], (String) a[1]));
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("field"));
PARSER.declareStringOrNull(ConstructingObjectParser.optionalConstructorArg(), new ParseField("format"));
}
/**
* Parse a {@link FieldAndFormat} from some {@link XContent}.
*/
public static FieldAndFormat fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
if (token.isValue()) {
return new FieldAndFormat(parser.text(), null);
} else {
return PARSER.apply(parser, null);
}
}
/** The name of the field. */
public final String field;
/** The format of the field, or {@code null} if defaults should be used. */
public final String format;
/** Sole constructor. */
public FieldAndFormat(String field, @Nullable String format) {
this.field = Objects.requireNonNull(field);
this.format = format;
}
/** Serialization constructor. */
public FieldAndFormat(StreamInput in) throws IOException {
this.field = in.readString();
if (in.getVersion().onOrAfter(Version.V_6_4_0)) {
format = in.readOptionalString();
} else {
format = null;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(field);
if (out.getVersion().onOrAfter(Version.V_6_4_0)) {
out.writeOptionalString(format);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldAndFormat that = (FieldAndFormat) o;
return Objects.equals(field, that.field) &&
Objects.equals(format, that.format);
}
@Override
public int hashCode() {
int h = field.hashCode();
h = 31 * h + Objects.hashCode(format);
return h;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(FIELD_FIELD.getPreferredName(), field);
if (format != null) {
builder.field(FORMAT_FIELD.getPreferredName(), format);
}
builder.endObject();
return builder;
}
}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.components;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.RequiredElement;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
/**
* Describes a service which is loaded on demand.
*
* <a href="http://www.jetbrains.org/intellij/sdk/docs/basics/plugin_structure/plugin_services.html">Plugin Services</a>
*/
public final class ServiceDescriptor {
public enum PreloadMode {
TRUE, FALSE, AWAIT, NOT_HEADLESS,
}
@Attribute
public String serviceInterface;
@Attribute
@RequiredElement
public String serviceImplementation;
@Attribute
public String testServiceImplementation;
@Attribute
public String headlessImplementation;
@Attribute
public boolean overrides;
/**
* Cannot be specified as part of {@link State} because to get annotation, class must be loaded, but it cannot be done for performance reasons.
*/
@Attribute
@ApiStatus.Experimental
@Nullable
public String configurationSchemaKey;
/**
* Preload service (before component creation). Not applicable for module level.
*
* Loading order and thread are not guaranteed, service should be decoupled as much as possible.
*/
@Attribute
@ApiStatus.Internal
public PreloadMode preload = ServiceDescriptor.PreloadMode.FALSE;
public String getInterface() {
return serviceInterface != null ? serviceInterface : getImplementation();
}
@Nullable
public String getImplementation() {
if (testServiceImplementation != null && ApplicationManager.getApplication().isUnitTestMode()) {
return testServiceImplementation;
}
else if (headlessImplementation != null && ApplicationManager.getApplication().isHeadlessEnvironment()) {
return headlessImplementation;
}
else {
return serviceImplementation;
}
}
@Override
public String toString() {
return "ServiceDescriptor(interface=" + getInterface() + ", implementation=" + getImplementation() + ")";
}
}
|
package io.codekvast.javaagent.codebase;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import io.codekvast.javaagent.config.AgentConfig;
import io.codekvast.javaagent.config.AgentConfigFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class CodeBaseFingerprintTest {
private final File[] files = new File[3];
private final AgentConfig config = AgentConfigFactory.createSampleAgentConfig();
@TempDir File tempDir;
@BeforeEach
public void beforeTest() {
for (int i = 0; i < files.length; i++) {
files[i] = new File(tempDir, "/foo" + i);
writeFile(files[i], "foo" + i);
}
}
@Test
public void should_be_equal_when_empty() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).build();
CodeBaseFingerprint fp2 = CodeBaseFingerprint.builder(config).build();
// when
// then
assertThat(fp1.getNumFiles(), is(0));
assertThat(fp2.getNumFiles(), is(0));
assertThat(fp1, equalTo(fp2));
}
@Test
public void should_not_be_equal_when_different_files() {
// given
CodeBaseFingerprint.Builder b1 = CodeBaseFingerprint.builder(config);
CodeBaseFingerprint.Builder b2 = CodeBaseFingerprint.builder(config);
// when
b1.record(files[1]);
CodeBaseFingerprint fp1 = b1.build();
b2.record(files[1]);
b2.record(files[2]);
CodeBaseFingerprint fp2 = b2.build();
// then
assertThat(fp1.getNumFiles(), is(1));
assertThat(fp2.getNumFiles(), is(2));
assertThat(fp1, not(equalTo(fp2)));
}
@Test
public void should_have_certain_value_when_empty() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).build();
// when
// then
assertThat(fp1.getNumFiles(), is(0));
assertThat(
fp1.getSha256(), is("78b39c00478151bba317c72111366d7bdf9aad67d880238527ea657791267142"));
}
@Test
public void should_be_insensitive_to_file_order() {
// given
CodeBaseFingerprint fp1 =
CodeBaseFingerprint.builder(config).record(files[1]).record(files[2]).build();
CodeBaseFingerprint fp2 =
CodeBaseFingerprint.builder(config).record(files[2]).record(files[1]).build();
// when
// then
assertThat(fp1, equalTo(fp2));
assertThat(fp2, equalTo(fp1));
}
@Test
public void should_ignore_duplicate_files() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).record(files[1]).build();
CodeBaseFingerprint fp2 =
CodeBaseFingerprint.builder(config).record(files[1]).record(files[1]).build();
// when
// then
assertThat(fp1.getNumFiles(), is(1));
assertThat(fp2.getNumFiles(), is(1));
assertThat(fp1, equalTo(fp2));
assertThat(fp2, equalTo(fp1));
}
@Test
public void should_include_last_modified_in_calculation() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).record(files[1]).build();
long now = 1492881351977L;
// when
files[1].setLastModified(now + 10);
CodeBaseFingerprint fp2 = CodeBaseFingerprint.builder(config).record(files[1]).build();
// then
assertThat(files[1].lastModified(), not(is(now)));
assertThat(fp2, not(equalTo(fp1)));
}
@Test
public void should_include_length_in_calculation() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).record(files[1]).build();
// when
writeFile(files[1], "foobar");
CodeBaseFingerprint fp2 = CodeBaseFingerprint.builder(config).record(files[1]).build();
// then
assertThat(fp2, not(equalTo(fp1)));
}
@Test
public void should_include_packages_in_calculation() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).build();
// when
CodeBaseFingerprint fp2 =
CodeBaseFingerprint.builder(
config.toBuilder().packages(config.getPackages() + "; some.more.packages").build())
.build();
// then
assertThat(fp2, not(equalTo(fp1)));
}
@Test
public void should_include_exclude_packages_in_calculation() {
// given
CodeBaseFingerprint fp1 = CodeBaseFingerprint.builder(config).build();
// when
CodeBaseFingerprint fp2 =
CodeBaseFingerprint.builder(
config.toBuilder()
.excludePackages(config.getExcludePackages() + "; some.more.packages")
.build())
.build();
// then
assertThat(fp2, not(equalTo(fp1)));
}
@Test
public void should_include_method_visibility_in_calculation() {
// given
CodeBaseFingerprint fp1 =
CodeBaseFingerprint.builder(config.toBuilder().methodVisibility("public").build()).build();
// when
CodeBaseFingerprint fp2 =
CodeBaseFingerprint.builder(config.toBuilder().methodVisibility("private").build()).build();
// then
assertThat(fp2, not(equalTo(fp1)));
}
@SneakyThrows
private void writeFile(File file, String contents) {
PrintWriter os = new PrintWriter(new FileWriter(file));
os.println(contents);
os.flush();
os.close();
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.indices;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class DateMathIndexExpressionsIntegrationIT extends ESIntegTestCase {
public void testIndexNameDateMathExpressions() {
DateTime now = new DateTime(DateTimeZone.UTC);
String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
createIndex(index1, index2, index3);
String dateMathExp1 = "<.marvel-{now/d}>";
String dateMathExp2 = "<.marvel-{now/d-1d}>";
String dateMathExp3 = "<.marvel-{now/d-2d}>";
client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
refresh();
SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
assertHitCount(searchResponse, 3);
assertSearchHits(searchResponse, "1", "2", "3");
GetResponse getResponse = client().prepareGet(dateMathExp1, "type", "1").get();
assertThat(getResponse.isExists(), is(true));
assertThat(getResponse.getId(), equalTo("1"));
getResponse = client().prepareGet(dateMathExp2, "type", "2").get();
assertThat(getResponse.isExists(), is(true));
assertThat(getResponse.getId(), equalTo("2"));
getResponse = client().prepareGet(dateMathExp3, "type", "3").get();
assertThat(getResponse.isExists(), is(true));
assertThat(getResponse.getId(), equalTo("3"));
IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
DeleteResponse deleteResponse = client().prepareDelete(dateMathExp1, "type", "1").get();
assertThat(deleteResponse.isFound(), equalTo(true));
assertThat(deleteResponse.getId(), equalTo("1"));
deleteResponse = client().prepareDelete(dateMathExp2, "type", "2").get();
assertThat(deleteResponse.isFound(), equalTo(true));
assertThat(deleteResponse.getId(), equalTo("2"));
deleteResponse = client().prepareDelete(dateMathExp3, "type", "3").get();
assertThat(deleteResponse.isFound(), equalTo(true));
assertThat(deleteResponse.getId(), equalTo("3"));
}
public void testAutoCreateIndexWithDateMathExpression() throws Exception {
DateTime now = new DateTime(DateTimeZone.UTC);
String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
String dateMathExp1 = "<.marvel-{now/d}>";
String dateMathExp2 = "<.marvel-{now/d-1d}>";
String dateMathExp3 = "<.marvel-{now/d-2d}>";
client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
refresh();
SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
assertHitCount(searchResponse, 3);
assertSearchHits(searchResponse, "1", "2", "3");
IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
}
public void testCreateIndexWithDateMathExpression() throws Exception {
DateTime now = new DateTime(DateTimeZone.UTC);
String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
String dateMathExp1 = "<.marvel-{now/d}>";
String dateMathExp2 = "<.marvel-{now/d-1d}>";
String dateMathExp3 = "<.marvel-{now/d-2d}>";
createIndex(dateMathExp1, dateMathExp2, dateMathExp3);
ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
assertThat(clusterState.metaData().index(index1), notNullValue());
assertThat(clusterState.metaData().index(index2), notNullValue());
assertThat(clusterState.metaData().index(index3), notNullValue());
}
}
|
package com.dvinfosys.widgets.Animation;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.graphics.drawable.Animatable2Compat;
import android.support.graphics.drawable.AnimatedVectorDrawableCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.util.Log;
import android.view.View;
public class CustomAnimDrawable extends BaseAnimDrawable {
private static final String TAG = "CustomAnimatedDrawable";
private View view;
@DrawableRes
private int resource;
@ColorInt
private int color;
private Rect bounds = new Rect();
private boolean mRunning;
private AnimatedVectorDrawableCompat animateDrawable;
private Animatable2Compat.AnimationCallback callback = new Animatable2Compat.AnimationCallback() {
@Override
public void onAnimationEnd(final Drawable drawable) {
Log.d(TAG, "onAnimationEnd");
animateDrawable.start();
view.invalidate();
}
};
public CustomAnimDrawable(View view, @DrawableRes int resource, @ColorInt int color) {
this.view = view;
this.resource = resource;
this.color = color;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
this.bounds = bounds;
setupAnimations();
}
@Override
public void start() {
Log.d(TAG, "start");
if (isRunning()) {
return;
}
mRunning = true;
animateDrawable.registerAnimationCallback(callback);
animateDrawable.start();
}
@Override
public void stop() {
Log.d(TAG, "stop");
if (!isRunning()) {
return;
}
mRunning = false;
animateDrawable.unregisterAnimationCallback(callback);
animateDrawable.stop();
}
@Override
public boolean isRunning() {
return mRunning;
}
@Override
public void draw(@NonNull Canvas canvas) {
animateDrawable.draw(canvas);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
@Override
public void setupAnimations() {
animateDrawable = AnimatedVectorDrawableCompat.create(view.getContext(), resource);
DrawableCompat.setTint(animateDrawable, color);
animateDrawable.setBounds(bounds);
}
@Override
public void dispose() {
animateDrawable = null;
}
}
|
package dominio;
public class Motorista extends Cobrador {
private String registroCnh;
private String categoriaCnh;
public String getRegistroCnh() {
return registroCnh;
}
public void setRegistroCnh(String registroCnh) {
this.registroCnh = registroCnh;
}
public String getCategoriaCnh() {
return categoriaCnh;
}
public void setCategoriaCnh(String categoriaCnh) {
this.categoriaCnh = categoriaCnh;
}
}
|
/*
* Created on February 8, 2007
*/
package com.ibm.ftt.api.samples.resources;
//=========================================================================
//
// Licensed Material - Property of IBM
//
// Copyright IBM Corp. 2007 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//=========================================================================
// These samples illustrates the use of the Remote Access API
// available in Rational Developer for System z. They are
// not intended for production use.
import java.util.Iterator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.rse.ui.SystemBasePlugin;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import com.ibm.ftt.resources.core.physical.IPhysicalResource;
import com.ibm.ftt.resources.core.physical.IResourceReference;
import com.ibm.ftt.resources.core.physical.util.OperationFailedException;
import com.ibm.ftt.resources.zos.zosphysical.impl.ZOSCatalog;
import com.ibm.ftt.resources.zos.zosphysical.impl.ZOSDataSet;
import com.ibm.ftt.resources.zos.zosphysical.impl.ZOSPartitionedDataSet;
import com.ibm.ftt.resources.zos.zosphysical.impl.ZOSResource;
/**
* Copies a physical resource. For simplicity, this sample uses the same container
* for the source and target resources and uses a fixed target name (depending on the
* resource type). It also is implemented only for MVS resources i.e. Partitioned
* Datasets, Sequential Datasets and Dataset members.
* @author longwell
*/
public class CopyPhysicalResourceAction implements IObjectActionDelegate {
private final static String SAMPLE_MEM_NAME = "SAMPMEM";
private final static String SAMPLE_SEQ_NAME = "SAMPSEQ";
private Object selectedItem;
/**
*
*/
public CopyPhysicalResourceAction() {
super();
}
/**
* Copy the resource.
*/
public void run(IAction action) {
// Make sure the selected item is valid
if (selectedItem == null) {
System.err.println("Copy Physical Resource Action - Selected resource must be a Physical Resource.");
return;
}
// Create variables for the source and it's container which will become the
// target folder
IPhysicalResource src = (IPhysicalResource)selectedItem;
IPhysicalResource targetFolder = (IPhysicalResource)src.getParent();
// Copying a PDS is not supported in this sample but would involve allocating
// a new PDS with the same characteristics as the source PDS and then copying
// each of the source PDS' members.
if(src instanceof ZOSPartitionedDataSet){
if(targetFolder instanceof ZOSCatalog || targetFolder instanceof ZOSPartitionedDataSet){
System.err.println("Copy Physical Resource Action - Copying a partitioned data set is not supported by this sample.");
return;
}
}
// See if the hardcoded target already exists. A null return string indicates that the
// copy operation should be aborted
String name = checkForCollision(targetFolder, src);
if (name == null)
return;
// For this sample we are only considering MVS resources i.e. no USS resources
if (src instanceof ZOSResource) {
ZOSResource srcPhysical = (ZOSResource)src;
try {
boolean force = true;
boolean lock = true;
IProgressMonitor monitor = null;
srcPhysical.copy(targetFolder, name, force, lock, monitor);
System.out.println("Copy Physical Resource Action - " + src.getName() + " successfully copied to " + name);
} catch (OperationFailedException e) {
System.err.println("Copy Physical Resource Action - Copy error: " + e.getMessage());
return;
}
}
}
/**
* See if the target of the copy already exists and if so prompt the user
* for permission to overwrite. In this case, the target name is hardcoded
* but it could be modified to accept a user supplied name.
*
* @param targetFolder Destination container of the copy
* @param src Source file to be copied
* @return The name of the target of the copy or null if the copy operation should
* be aborted.
*/
String checkForCollision(IPhysicalResource targetFolder, IPhysicalResource src) {
String newName = null;
String srcName = src.getName();
boolean collision = false;
ZOSDataSet existingDataset = null;
// Handle PDS members differently from Sequential datasets
if (targetFolder instanceof ZOSPartitionedDataSet) {
newName = SAMPLE_MEM_NAME;
ZOSPartitionedDataSet ds = (ZOSPartitionedDataSet)targetFolder;
if (ds.findMember(newName) != null) {
collision = true;
// Remove extension for the message dialog
int index = srcName.lastIndexOf(".");
srcName = srcName.substring(0, index);
}
} else if (targetFolder instanceof ZOSCatalog) {
int index = srcName.indexOf(".");
newName = srcName.substring(0, index + 1);
newName = newName + SAMPLE_SEQ_NAME; // PDS not supported
ZOSCatalog catalog = (ZOSCatalog)targetFolder;
existingDataset = (ZOSDataSet)catalog.findMember(newName);
if ( existingDataset != null) {
collision = true;
}
}
// Prompt the user to see if they want to overwrite an existing target
if (collision) {
MessageDialog dlg = new MessageDialog(
SystemBasePlugin.getActiveWorkbenchShell(),
"Copy Physical Resource (Sample)",
null,
"The sample is attempting to copy " + srcName + " to "
+ newName + " in " + targetFolder.getName() + " but " + newName
+ " already exists. Do you want to overwrite " + newName + "?",
MessageDialog.WARNING,
new String[] {"Yes", "No"},
0);
dlg.open();
if (dlg.getReturnCode() == 1) { // Index of "No" in button label array
newName = null; // Abort copy
} else {
// When overwriting a dataset, we need to delete the existing dataset before copying
if (existingDataset != null) {
boolean force = true;
IProgressMonitor monitor = null;
try {
existingDataset.delete(force, monitor);
}
catch(OperationFailedException e) {
System.err.println("Copy Physical Resource Action - Error trying to delete existing dataset "
+ newName + " before copying: " + e.getMessage());
newName = null; // Abort copy
}
}
}
}
return newName;
}
/**
* Use the first Physical Resource in the selection.
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
selectedItem = null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection currentSelection = (IStructuredSelection) selection;
Iterator iterator = currentSelection.iterator();
while (iterator.hasNext()) {
Object item = iterator.next();
if (item instanceof IResourceReference) {
item = ((IResourceReference) item).getReferent();
if (item instanceof IPhysicalResource) {
selectedItem = item;
break;
}
}
}
}
}
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
// Not used
}
}
|
// Copyright 2017 The Bazel Authors. 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.google.devtools.build.skyframe;
/** Use when only a single evaluation of the graph with a single constant version is expected. */
public class ConstantVersion implements Version {
public static final ConstantVersion INSTANCE = new ConstantVersion();
private ConstantVersion() {}
@Override
public boolean atMost(Version other) {
return this.equals(other);
}
}
|
/* Copyright 2004-2019 Jim Voris
*
* 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.qumasoft.server;
import com.qumasoft.qvcslib.LabelInfo;
import com.qumasoft.qvcslib.LogFileHeaderInfo;
import com.qumasoft.qvcslib.LogFileReadException;
import com.qumasoft.qvcslib.QVCSException;
import com.qumasoft.qvcslib.commandargs.UnLabelRevisionCommandArgs;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Operation to remove a label.
*
* @author Jim Voris
*/
class LogFileOperationUnLabelRevision extends AbstractLogFileOperation {
private final UnLabelRevisionCommandArgs commandLineArgs;
private final String userName;
private final String labelString; // This is label we remove
private final String shortWorkfileName;
private RandomAccessFile newArchiveStream;
private RandomAccessFile oldArchiveStream;
// Create our logger object
private static final Logger LOGGER = LoggerFactory.getLogger(LogFileOperationUnLabelRevision.class);
/**
* Creates a new instance of LogFileOperationUnLabelRevision.
* @param args command arguments.
*/
LogFileOperationUnLabelRevision(Object[] args) {
super(args, (LogFileImpl) args[0]);
commandLineArgs = (UnLabelRevisionCommandArgs) args[1];
userName = commandLineArgs.getUserName();
labelString = commandLineArgs.getLabelString();
shortWorkfileName = commandLineArgs.getShortWorkfileName();
}
@Override
public boolean execute() throws QVCSException {
return unLabelRevision();
}
private boolean unLabelRevision() throws QVCSException {
boolean retVal = false;
if (!getLogFileImpl().isArchiveInformationRead()) {
retVal = getLogFileImpl().readInformation();
}
// Make sure user is on the access list.
getLogFileImpl().makeSureIsOnAccessList(userName);
// Make sure we are removing a label string that exists.
boolean labelFound = false;
int labelIndex = -1;
LabelInfo[] existingLabels = getLogFileImpl().getLogFileHeaderInfo().getLabelInfo();
if (existingLabels != null) {
for (int i = 0; i < existingLabels.length; i++) {
String existingLabel = existingLabels[i].getLabelString();
if (existingLabel.equals(labelString)) {
labelFound = true;
labelIndex = i;
break;
}
}
}
if (labelFound) {
// Delete the temp file for sure. We need the temp file gone, since
// we need to create the new archive file and it will be smaller
// than the existing archive file.
getLogFileImpl().getTempFile().delete();
try {
newArchiveStream = new java.io.RandomAccessFile(getLogFileImpl().getTempFile(), "rw");
oldArchiveStream = new java.io.RandomAccessFile(getLogFileImpl().getFile(), "r");
// Create a new LabelInfo array that's one smaller than before
LabelInfo[] oldLabelInfo = getLogFileImpl().getLogFileHeaderInfo().getLabelInfo();
int newLabelInfoSize = oldLabelInfo.length - 1;
if (newLabelInfoSize == 0) {
// Clear all label information.
getLogFileImpl().getLogFileHeaderInfo().setLabelInfo(null);
} else {
LabelInfo[] newLabelInfo = new LabelInfo[newLabelInfoSize];
// Copy the existing labels to the new label info array, leaving
// out the one we are deleting.
int j = 0;
for (int i = 0; i < oldLabelInfo.length; i++) {
if (i != labelIndex) {
newLabelInfo[j++] = oldLabelInfo[i];
}
}
// Set the label information.
getLogFileImpl().getLogFileHeaderInfo().setLabelInfo(newLabelInfo);
}
// Write the header information to the stream.
getLogFileImpl().getLogFileHeaderInfo().write(newArchiveStream);
// Position the old archive to the end of the header area.
LogFileHeaderInfo oldHeaderInfo = new LogFileHeaderInfo();
oldHeaderInfo.read(oldArchiveStream);
// Figure out how many bytes remain in the original that need to
// be copied to the new archive.
long numberOfBytesToCopyFromSource = oldArchiveStream.length() - oldArchiveStream.getFilePointer();
// Copy the rest of the original archive to the new archive.
copyFromOneOpenFileToAnotherOpenFile(oldArchiveStream, newArchiveStream, numberOfBytesToCopyFromSource);
retVal = true;
} catch (LogFileReadException | IOException e) {
LOGGER.warn(e.getLocalizedMessage(), e);
retVal = false;
} finally {
try {
if (oldArchiveStream != null) {
oldArchiveStream.close();
}
if (newArchiveStream != null) {
newArchiveStream.close();
}
} catch (IOException e) {
LOGGER.warn(e.getLocalizedMessage(), e);
retVal = false;
}
}
// Replace existing archive with new one.
if (retVal) {
getLogFileImpl().replaceExistingArchiveWithNewTempArchive();
} else {
getLogFileImpl().getTempFile().delete();
}
} else {
String errorMessage = "Label not found: [" + labelString + "] in " + shortWorkfileName;
commandLineArgs.setErrorMessage(errorMessage);
LOGGER.info(errorMessage);
}
return retVal;
}
}
|
/*
* Copyright 2016-2021 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.ecr.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/CompleteLayerUpload" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CompleteLayerUploadResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The registry ID associated with the request.
* </p>
*/
private String registryId;
/**
* <p>
* The repository name associated with the request.
* </p>
*/
private String repositoryName;
/**
* <p>
* The upload ID associated with the layer.
* </p>
*/
private String uploadId;
/**
* <p>
* The <code>sha256</code> digest of the image layer.
* </p>
*/
private String layerDigest;
/**
* <p>
* The registry ID associated with the request.
* </p>
*
* @param registryId
* The registry ID associated with the request.
*/
public void setRegistryId(String registryId) {
this.registryId = registryId;
}
/**
* <p>
* The registry ID associated with the request.
* </p>
*
* @return The registry ID associated with the request.
*/
public String getRegistryId() {
return this.registryId;
}
/**
* <p>
* The registry ID associated with the request.
* </p>
*
* @param registryId
* The registry ID associated with the request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompleteLayerUploadResult withRegistryId(String registryId) {
setRegistryId(registryId);
return this;
}
/**
* <p>
* The repository name associated with the request.
* </p>
*
* @param repositoryName
* The repository name associated with the request.
*/
public void setRepositoryName(String repositoryName) {
this.repositoryName = repositoryName;
}
/**
* <p>
* The repository name associated with the request.
* </p>
*
* @return The repository name associated with the request.
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* <p>
* The repository name associated with the request.
* </p>
*
* @param repositoryName
* The repository name associated with the request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompleteLayerUploadResult withRepositoryName(String repositoryName) {
setRepositoryName(repositoryName);
return this;
}
/**
* <p>
* The upload ID associated with the layer.
* </p>
*
* @param uploadId
* The upload ID associated with the layer.
*/
public void setUploadId(String uploadId) {
this.uploadId = uploadId;
}
/**
* <p>
* The upload ID associated with the layer.
* </p>
*
* @return The upload ID associated with the layer.
*/
public String getUploadId() {
return this.uploadId;
}
/**
* <p>
* The upload ID associated with the layer.
* </p>
*
* @param uploadId
* The upload ID associated with the layer.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompleteLayerUploadResult withUploadId(String uploadId) {
setUploadId(uploadId);
return this;
}
/**
* <p>
* The <code>sha256</code> digest of the image layer.
* </p>
*
* @param layerDigest
* The <code>sha256</code> digest of the image layer.
*/
public void setLayerDigest(String layerDigest) {
this.layerDigest = layerDigest;
}
/**
* <p>
* The <code>sha256</code> digest of the image layer.
* </p>
*
* @return The <code>sha256</code> digest of the image layer.
*/
public String getLayerDigest() {
return this.layerDigest;
}
/**
* <p>
* The <code>sha256</code> digest of the image layer.
* </p>
*
* @param layerDigest
* The <code>sha256</code> digest of the image layer.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CompleteLayerUploadResult withLayerDigest(String layerDigest) {
setLayerDigest(layerDigest);
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 (getRegistryId() != null)
sb.append("RegistryId: ").append(getRegistryId()).append(",");
if (getRepositoryName() != null)
sb.append("RepositoryName: ").append(getRepositoryName()).append(",");
if (getUploadId() != null)
sb.append("UploadId: ").append(getUploadId()).append(",");
if (getLayerDigest() != null)
sb.append("LayerDigest: ").append(getLayerDigest());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CompleteLayerUploadResult == false)
return false;
CompleteLayerUploadResult other = (CompleteLayerUploadResult) obj;
if (other.getRegistryId() == null ^ this.getRegistryId() == null)
return false;
if (other.getRegistryId() != null && other.getRegistryId().equals(this.getRegistryId()) == false)
return false;
if (other.getRepositoryName() == null ^ this.getRepositoryName() == null)
return false;
if (other.getRepositoryName() != null && other.getRepositoryName().equals(this.getRepositoryName()) == false)
return false;
if (other.getUploadId() == null ^ this.getUploadId() == null)
return false;
if (other.getUploadId() != null && other.getUploadId().equals(this.getUploadId()) == false)
return false;
if (other.getLayerDigest() == null ^ this.getLayerDigest() == null)
return false;
if (other.getLayerDigest() != null && other.getLayerDigest().equals(this.getLayerDigest()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRegistryId() == null) ? 0 : getRegistryId().hashCode());
hashCode = prime * hashCode + ((getRepositoryName() == null) ? 0 : getRepositoryName().hashCode());
hashCode = prime * hashCode + ((getUploadId() == null) ? 0 : getUploadId().hashCode());
hashCode = prime * hashCode + ((getLayerDigest() == null) ? 0 : getLayerDigest().hashCode());
return hashCode;
}
@Override
public CompleteLayerUploadResult clone() {
try {
return (CompleteLayerUploadResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
/*
* Aipo is a groupware program developed by Aimluck,Inc.
* Copyright (C) 2004-2011 Aimluck,Inc.
* http://www.aipo.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aimluck.eip.account;
import java.util.List;
import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.JetspeedUserManagement;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;
import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.cellular.util.CellularUtils;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALBaseUser;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.util.ALCellularUtils;
import com.aimluck.eip.util.ALEipUtils;
/**
*/
public class CellAccountEasyLoginFormData extends ALAbstractFormData {
/** logger */
private static final JetspeedLogger logger = JetspeedLogFactoryService
.getLogger(CellAccountEasyLoginFormData.class.getName());
/** 携帯電話の固有 ID */
private ALStringField cellular_uid;
/** 携帯電話からのアクセス用キー */
private String key;
private ALBaseUser baseUser;
private boolean enableEasyLogin = false;
private String cellular_url;
/**
* 初期化します。
*
* @param action
* @param rundata
* @param context
*
*
*/
@Override
public void init(ALAction action, RunData rundata, Context context)
throws ALPageNotFoundException, ALDBErrorException {
super.init(action, rundata, context);
try {
JetspeedRunData jdata = (JetspeedRunData) rundata;
try {
// 最新のユーザ情報を取得する.
baseUser =
(ALBaseUser) JetspeedUserManagement.getUser(new UserNamePrincipal(
jdata.getJetspeedUser().getUserName()));
} catch (JetspeedSecurityException e) {
baseUser = (ALBaseUser) rundata.getUser();
}
cellular_url = CellularUtils.getCellularUrl(rundata, context);
String uid = baseUser.getCelluarUId();
enableEasyLogin = (uid != null && uid.length() > 0);
} catch (Exception e) {
logger.error("CellAccountEasyLoginFormData.init", e);
ALEipUtils.redirectPageNotFound(rundata);
return;
}
}
/**
*
*/
@Override
public void initField() {
// 携帯電話の固有 ID
cellular_uid = new ALStringField();
cellular_uid.setFieldName("携帯電話の固有 ID");
cellular_uid.setTrim(true);
}
/**
*
*/
@Override
protected void setValidator() {
// 携帯電話の固有 ID
cellular_uid.setNotNull(true);
cellular_uid.setCharacterType(ALStringField.TYPE_ALPHABET_NUMBER);
cellular_uid.limitMaxLength(50);
}
/**
*
*/
@Override
protected boolean validate(List<String> msgList) {
cellular_uid.validate(msgList);
return (msgList.size() == 0);
}
/**
*
* @param rundata
* @param context
* @param msgList
* @return
*/
@Override
protected boolean loadFormData(RunData rundata, Context context,
List<String> msgList) {
return false;
}
/**
*
* @param rundata
* @param context
* @param msgList
* @return
*/
@Override
protected boolean insertFormData(RunData rundata, Context context,
List<String> msgList) {
try {
// 携帯電話の固有 ID
baseUser.setCelluarUId(cellular_uid.getValue());
// ユーザー情報を更新
JetspeedSecurity.saveUser(baseUser);
} catch (Exception ex) {
logger.error("CellAccountEasyLoginFormData.insertFormData", ex);
return false;
}
return true;
}
/**
*
* @param rundata
* @param context
* @param msgList
* @return
*/
@Override
protected boolean updateFormData(RunData rundata, Context context,
List<String> msgList) {
return false;
}
/**
*
* @param rundata
* @param context
* @param msgList
* @return
*/
@Override
protected boolean deleteFormData(RunData rundata, Context context,
List<String> msgList) {
try {
// 携帯電話の固有 ID
baseUser.setCelluarUId("");
// ユーザー情報を更新
JetspeedSecurity.saveUser(baseUser);
} catch (Exception ex) {
logger.error("CellAccountEasyLoginFormData.deleteFormData", ex);
return false;
}
return true;
}
/**
*
* @param rundata
* @param context
* @param msgList
* @return
*/
@Override
protected boolean setFormData(RunData rundata, Context context,
List<String> msgList) throws ALPageNotFoundException, ALDBErrorException {
boolean res = super.setFormData(rundata, context, msgList);
if (res) {
String celluid = ALCellularUtils.getCellularUid(rundata);
cellular_uid.setValue(celluid);
key =
baseUser.getUserName()
+ "_"
+ ALCellularUtils.getCheckValueForCellLogin(
baseUser.getUserName(),
baseUser.getUserId());
}
return res;
}
public ALStringField getCellularUid() {
return cellular_uid;
}
public boolean enableEasyLogin() {
return enableEasyLogin;
}
public String getKey() {
return key;
}
public String getCellularUrl() {
return cellular_url;
}
}
|
package com.ray3k.skincomposer.dialog.scenecomposer.undoables;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerModel;
public class CheckBoxCheckedUndoable implements SceneComposerUndoable {
private DialogSceneComposerModel.SimCheckBox checkBox;
private DialogSceneComposer dialog;
private boolean checked;
private boolean previousChecked;
public CheckBoxCheckedUndoable(boolean checked) {
this.checked = checked;
dialog = DialogSceneComposer.dialog;
checkBox = (DialogSceneComposerModel.SimCheckBox) dialog.simActor;
previousChecked = checkBox.checked;
}
@Override
public void undo() {
checkBox.checked = previousChecked;
if (dialog.simActor != checkBox) {
dialog.simActor = checkBox;
dialog.populateProperties();
dialog.populatePath();
}
dialog.model.updatePreview();
}
@Override
public void redo() {
checkBox.checked = checked;
if (dialog.simActor != checkBox) {
dialog.simActor = checkBox;
dialog.populateProperties();
dialog.populatePath();
}
dialog.model.updatePreview();
}
@Override
public String getRedoString() {
return "Redo \"CheckBox checked " + checked + "\"";
}
@Override
public String getUndoString() {
return "Undo \"CheckBox checked " + checked + "\"";
}
}
|
package com.leeue.mapper;
import com.leeue.api.entity.StockEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface StockMapper {
@Select("SELECT id as id ,commodity_id as commodityId, stock as stock from stock where commodity_id=#{commodityId}")
public StockEntity selectStock(@Param("commodityId") Long commodityId);
@Update("update stock set stock=stock-1 where commodity_id=#{commodityId}")
public int updateStock(@Param("commodityId") Long commodityId);
}
|
package com.softsquared.template.src.main.Home;
import com.softsquared.template.src.main.Home.interfaces.HomeFragView;
import com.softsquared.template.src.main.Home.interfaces.HomeRetrofitInterface;
import com.softsquared.template.src.main.Home.models.FragHomeResponse;
import com.softsquared.template.src.main.Home.models.postInfo;
import com.softsquared.template.src.main.interfaces.MainActivityView;
import com.softsquared.template.src.main.interfaces.MainRetrofitInterface;
import com.softsquared.template.src.main.models.DefaultResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.softsquared.template.src.ApplicationClass.getRetrofit;
class HomeFragService {
private final HomeFragView mHomeFragView; //
HomeFragService(final HomeFragView homeFragView) {
this.mHomeFragView = homeFragView;
}
void getHome() { //서버통신
//비동기 방식 != 순차적
final HomeRetrofitInterface homeRetrofitInterface = getRetrofit().create(HomeRetrofitInterface.class);
homeRetrofitInterface.getHome().enqueue(new Callback<FragHomeResponse>() {
@Override
public void onResponse(Call<FragHomeResponse> call, Response<FragHomeResponse> response) {
final FragHomeResponse fragHomeResponse = response.body(); //response:서버에서 받아온 값
//DefaultResponse는 자동으로 값을 파싱해줌
if (fragHomeResponse == null) {
mHomeFragView.validateFailure(null);
return;
}
mHomeFragView.validateSuccess(fragHomeResponse.getMessage());
//mHomeFragView.homeRecommendSuccess(FragHomeResponse.getPostList());
//성공하면 파싱한 값을 넘겨줌
//MainActivity에 있는 validateFailure(),validateSuccess()가 돌게됨
}
@Override
public void onFailure(Call<FragHomeResponse> call, Throwable t) { //통신실패
mHomeFragView.validateFailure(null);
}
});
}
}
|
package mil.nga.giat.mage.sdk.http.converter;
import java.io.IOException;
import java.util.List;
import mil.nga.giat.mage.sdk.datastore.location.Location;
import mil.nga.giat.mage.sdk.datastore.user.Event;
import mil.nga.giat.mage.sdk.jackson.deserializer.LocationDeserializer;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* Retrofit location response body converter
*
* Handles Jackson deserialization for locations
*
* @author newmanw
*
*/
public class LocationResponseBodyConverter implements Converter<ResponseBody, List<Location>> {
private final Event event;
private final boolean groupByUser;
public LocationResponseBodyConverter(Event event, boolean groupByUser) {
this.event = event;
this.groupByUser = groupByUser;
}
@Override
public List<Location> convert(ResponseBody body) throws IOException {
LocationDeserializer deserializer = new LocationDeserializer(event);
return groupByUser ?
deserializer.parseUserLocations(body.byteStream()) :
deserializer.parseLocations(body.byteStream());
}
}
|
package upstart.b4.incremental;
import upstart.util.collect.PairStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.function.Function;
import java.util.stream.Stream;
public interface BuildDependency {
static BuildDependency structural(BuildSources sources, Function<Path, Stream<Path>> pathTransformer) {
try (Stream<PathInfo> sourceInfo = sources.paths()) {
return PairStream.withMappedValues(sourceInfo
.filter(PathInfo::isRegularFile)
.map(PathInfo::path),
pathTransformer
).map((source, targets) -> FileBuildDependency.of(BuildSources.of(source), BuildTargets.of(targets)))
.reduce(BuildDependency::merge)
.orElseThrow(() -> new IllegalArgumentException("No sources found"));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
boolean requiresRebuild();
default BuildDependency merge(BuildDependency other) {
return () -> requiresRebuild() || other.requiresRebuild();
}
}
|
package mage.cards.d;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.mana.BlackManaAbility;
import mage.abilities.mana.BlueManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
/**
*
* @author TheElk801
*/
public final class DimirLocket extends CardImpl {
public DimirLocket(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}");
// {T}: Add {U} or {B}.
this.addAbility(new BlueManaAbility());
this.addAbility(new BlackManaAbility());
// {U/B}{U/B}{U/B}{U/B}, {T}, Sacrifice Dimir Locket: Draw two cards.
Ability ability = new SimpleActivatedAbility(
new DrawCardSourceControllerEffect(2),
new ManaCostsImpl("{U/B}{U/B}{U/B}{U/B}")
);
ability.addCost(new TapSourceCost());
ability.addCost(new SacrificeSourceCost());
this.addAbility(ability);
}
private DimirLocket(final DimirLocket card) {
super(card);
}
@Override
public DimirLocket copy() {
return new DimirLocket(this);
}
}
|
/*
* 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.hive.ql.exec.mr3.dag;
import com.datamonad.mr3.DAGAPI;
import com.datamonad.mr3.api.common.MR3Conf;
import java.util.Set;
public class TaskLocationHint {
private final Set<String> hosts;
private final Set<String> racks;
public TaskLocationHint(
Set<String> hosts,
Set<String> racks) {
this.hosts = hosts;
this.racks = racks;
}
// DAGProto Conversion utilities
public DAGAPI.TaskLocationHintProto createTaskLocationHintProto() {
return DAGAPI.TaskLocationHintProto.newBuilder()
.addAllHosts(hosts)
.addAllRacks(racks)
.build();
}
}
|
/*
* 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.kylin.cube.model.validation.rule;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.kylin.cube.model.CubeDesc;
import org.apache.kylin.cube.model.DimensionDesc;
import org.apache.kylin.cube.model.validation.IValidatorRule;
import org.apache.kylin.cube.model.validation.ResultLevel;
import org.apache.kylin.cube.model.validation.ValidateContext;
import org.apache.kylin.measure.topn.TopNMeasureType;
import org.apache.kylin.metadata.MetadataManager;
import org.apache.kylin.metadata.model.ColumnDesc;
import org.apache.kylin.metadata.model.FunctionDesc;
import org.apache.kylin.metadata.model.MeasureDesc;
import org.apache.kylin.metadata.model.ParameterDesc;
import org.apache.kylin.metadata.model.TableDesc;
import com.google.common.collect.Lists;
/**
* Validate function parameter.
* <p/>
* if type is column, check values are valid fact table columns if type is
* constant, the value only can be numberic
* <p/>
* the return type only can be int/bigint/long/double/decimal
*
*/
public class FunctionRule implements IValidatorRule<CubeDesc> {
/*
* (non-Javadoc)
*
* @see
* org.apache.kylin.metadata.validation.IValidatorRule#validate(java.lang.Object
* , org.apache.kylin.metadata.validation.ValidateContext)
*/
@Override
public void validate(CubeDesc cube, ValidateContext context) {
List<MeasureDesc> measures = cube.getMeasures();
if (validateMeasureNamesDuplicated(measures, context)) {
return;
}
List<FunctionDesc> countFuncs = new ArrayList<FunctionDesc>();
Iterator<MeasureDesc> it = measures.iterator();
while (it.hasNext()) {
MeasureDesc measure = it.next();
FunctionDesc func = measure.getFunction();
ParameterDesc parameter = func.getParameter();
if (parameter == null) {
context.addResult(ResultLevel.ERROR, "Must define parameter for function " + func.getExpression() + " in " + measure.getName());
return;
}
String type = func.getParameter().getType();
String value = func.getParameter().getValue();
if (StringUtils.isEmpty(type)) {
context.addResult(ResultLevel.ERROR, "Must define type for parameter type " + func.getExpression() + " in " + measure.getName());
return;
}
if (StringUtils.isEmpty(value)) {
context.addResult(ResultLevel.ERROR, "Must define type for parameter value " + func.getExpression() + " in " + measure.getName());
return;
}
if (StringUtils.isEmpty(func.getReturnType())) {
context.addResult(ResultLevel.ERROR, "Must define return type for function " + func.getExpression() + " in " + measure.getName());
return;
}
if (StringUtils.equalsIgnoreCase(FunctionDesc.PARAMETER_TYPE_COLUMN, type)) {
validateColumnParameter(context, cube, value);
} else if (StringUtils.equals(FunctionDesc.PARAMETER_TYPE_CONSTANT, type)) {
validateCostantParameter(context, cube, value);
}
try {
func.getMeasureType().validate(func);
} catch (IllegalArgumentException ex) {
context.addResult(ResultLevel.ERROR, ex.getMessage());
}
if (func.isCount())
countFuncs.add(func);
if (TopNMeasureType.FUNC_TOP_N.equalsIgnoreCase(func.getExpression())) {
if (parameter.getNextParameter() == null) {
context.addResult(ResultLevel.ERROR, "Must define at least 2 parameters for function " + func.getExpression() + " in " + measure.getName());
return;
}
ParameterDesc groupByCol = parameter.getNextParameter();
List<String> duplicatedCol = Lists.newArrayList();
while (groupByCol != null) {
String embeded_groupby = groupByCol.getValue();
for (DimensionDesc dimensionDesc : cube.getDimensions()) {
if (dimensionDesc.getColumn() != null && dimensionDesc.getColumn().equalsIgnoreCase(embeded_groupby)) {
duplicatedCol.add(embeded_groupby);
}
}
groupByCol = groupByCol.getNextParameter();
}
if (duplicatedCol.size() > 0) {
context.addResult(ResultLevel.ERROR, "Couldn't use " + duplicatedCol.toString() + " in Top-N as it is already defined as dimension.");
return;
}
}
}
if (countFuncs.size() != 1) {
context.addResult(ResultLevel.ERROR, "Must define one and only one count(1) function, but there are " + countFuncs.size() + " -- " + countFuncs);
}
}
/**
* @param context
* @param cube
* @param value
*/
private void validateCostantParameter(ValidateContext context, CubeDesc cube, String value) {
try {
Integer.parseInt(value);
} catch (Exception e) {
context.addResult(ResultLevel.ERROR, "Parameter value must be number, but it is " + value);
}
}
/**
* @param context
* @param cube
* @param value
*/
private void validateColumnParameter(ValidateContext context, CubeDesc cube, String value) {
String factTable = cube.getFactTable();
if (StringUtils.isEmpty(factTable)) {
context.addResult(ResultLevel.ERROR, "Fact table can not be null.");
return;
}
TableDesc table = MetadataManager.getInstance(cube.getConfig()).getTableDesc(factTable);
if (table == null) {
context.addResult(ResultLevel.ERROR, "Fact table can not be found: " + cube);
return;
}
// Prepare column set
Set<String> set = new HashSet<String>();
ColumnDesc[] cdesc = table.getColumns();
for (int i = 0; i < cdesc.length; i++) {
ColumnDesc columnDesc = cdesc[i];
set.add(columnDesc.getName());
}
String[] items = value.split(",");
for (int i = 0; i < items.length; i++) {
String item = items[i].trim();
if (StringUtils.isEmpty(item)) {
continue;
}
if (!set.contains(item)) {
context.addResult(ResultLevel.ERROR, "Column [" + item + "] does not exist in factable table" + factTable);
}
}
}
/**
* @param measures
*/
private boolean validateMeasureNamesDuplicated(List<MeasureDesc> measures, ValidateContext context) {
Set<String> nameSet = new HashSet<>();
for (MeasureDesc measure: measures){
if (nameSet.contains(measure.getName())){
context.addResult(ResultLevel.ERROR, "There is duplicated measure's name: " + measure.getName());
return true;
} else {
nameSet.add(measure.getName());
}
}
return false;
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.apimanagement.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The ApiIssuesCreateOrUpdateHeaders model. */
@Fluent
public final class ApiIssuesCreateOrUpdateHeaders {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ApiIssuesCreateOrUpdateHeaders.class);
/*
* The Etag property.
*/
@JsonProperty(value = "Etag")
private String etag;
/**
* Get the etag property: The Etag property.
*
* @return the etag value.
*/
public String etag() {
return this.etag;
}
/**
* Set the etag property: The Etag property.
*
* @param etag the etag value to set.
* @return the ApiIssuesCreateOrUpdateHeaders object itself.
*/
public ApiIssuesCreateOrUpdateHeaders withEtag(String etag) {
this.etag = etag;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// 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
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import java.util.Collections;
import java.util.Set;
import com.google.common.collect.Sets;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
/**
* <p>
* Throwing java.lang.Error or java.lang.RuntimeException
* is almost never acceptable.
* </p>
* Check has following properties:
* <p>
* <b>illegalClassNames</b> - throw class names to reject.
* </p>
* <p>
* <b>ignoredMethodNames</b> - names of methods to ignore.
* </p>
* <p>
* <b>ignoreOverriddenMethods</b> - ignore checking overridden methods (marked with Override
* or java.lang.Override annotation) default value is <b>true</b>.
* </p>
*
* @author Oliver Burn
* @author John Sirois
* @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
*/
public final class IllegalThrowsCheck extends AbstractIllegalCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "illegal.throw";
/** Default ignored method names. */
private static final String[] DEFAULT_IGNORED_METHOD_NAMES = {
"finalize",
};
/** Property for ignoring overridden methods. */
private boolean ignoreOverriddenMethods = true;
/** Methods which should be ignored. */
private final Set<String> ignoredMethodNames = Sets.newHashSet();
/** Creates new instance of the check. */
public IllegalThrowsCheck() {
super("Error", "RuntimeException", "Throwable", "java.lang.Error",
"java.lang.RuntimeException", "java.lang.Throwable");
setIgnoredMethodNames(DEFAULT_IGNORED_METHOD_NAMES);
}
@Override
public int[] getDefaultTokens() {
return new int[] {TokenTypes.LITERAL_THROWS};
}
@Override
public int[] getRequiredTokens() {
return getDefaultTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {TokenTypes.LITERAL_THROWS};
}
@Override
public void visitToken(DetailAST detailAST) {
final DetailAST methodDef = detailAST.getParent();
DetailAST token = detailAST.getFirstChild();
// Check if the method with the given name should be ignored.
if (!isIgnorableMethod(methodDef)) {
while (token != null) {
if (token.getType() != TokenTypes.COMMA) {
final FullIdent ident = FullIdent.createFullIdent(token);
if (isIllegalClassName(ident.getText())) {
log(token, MSG_KEY, ident.getText());
}
}
token = token.getNextSibling();
}
}
}
/**
* Checks if current method is ignorable due to Check's properties.
* @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF}
* @return true if method is ignorable.
*/
private boolean isIgnorableMethod(DetailAST methodDef) {
return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText())
|| ignoreOverriddenMethods
&& (AnnotationUtility.containsAnnotation(methodDef, "Override")
|| AnnotationUtility.containsAnnotation(methodDef, "java.lang.Override"));
}
/**
* Check if the method is specified in the ignore method list.
* @param name the name to check
* @return whether the method with the passed name should be ignored
*/
private boolean shouldIgnoreMethod(String name) {
return ignoredMethodNames.contains(name);
}
/**
* Set the list of ignore method names.
* @param methodNames array of ignored method names
*/
public void setIgnoredMethodNames(String... methodNames) {
ignoredMethodNames.clear();
Collections.addAll(ignoredMethodNames, methodNames);
}
/**
* Sets <b>ignoreOverriddenMethods</b> property value.
* @param ignoreOverriddenMethods Check's property.
*/
public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
this.ignoreOverriddenMethods = ignoreOverriddenMethods;
}
}
|
package com.adobe.phonegap.push;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.iid.InstanceID;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import me.leolin.shortcutbadger.ShortcutBadger;
import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.SdkConstants;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.*;
public class PushPlugin extends CordovaPlugin implements PushConstants {
public static final String LOG_TAG = "PushPlugin";
private static CallbackContext pushContext;
private static CordovaWebView gWebView;
private static Bundle gCachedExtras = null;
private static boolean gForeground = false;
/**
* Gets the application context from cordova's main activity.
* @return the application context
*/
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
private void initOneSDK(final Context applicationContext,final JSONArray data, final CallbackContext callbackContext){
Log.d(LOG_TAG, "get App Package name : " + applicationContext.getPackageName());
AlibabaSDK.asyncInit(applicationContext, new InitResultCallback(){
public void onSuccess(){
Log.e(LOG_TAG, "init onesdk success");
initAliyunCloudChannel(applicationContext, data, callbackContext);
}
public void onFailure(int code, String message){
Log.e(LOG_TAG, "init onesdk failed : " + message);
}
});
}
private void initAliyunCloudChannel(Context applicationContext, final JSONArray data, final CallbackContext callbackContext){
PushServiceFactory.init(applicationContext);
CloudPushService pushService = PushServiceFactory.getCloudPushService();
// 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
MiPushRegister.register(applicationContext, "2882303761517334757", "5281733465757");
// 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
HuaWeiRegister.register(applicationContext);
pushService.register(applicationContext, new CommonCallback(){
@Override
public void onSuccess(String response){
Log.d(LOG_TAG, "init AliyunCloudChannel success, device id : " + PushServiceFactory.getCloudPushService().getDeviceId() + ",UtDid: " + PushServiceFactory.getCloudPushService().getUTDeviceId() + ", Appkey: " + AlibabaSDK.getGlobalProperty(SdkConstants.APP_KEY));
initPush(data, callbackContext);
}
@Override
public void onFailed(String errorCode, String errorMessage){
Log.d(LOG_TAG, "init AliyunCloudChannel failed --errorCode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
}
private void initPush(final JSONArray data, final CallbackContext callbackContext){
pushContext = callbackContext;
JSONObject jo = null;
Log.v(LOG_TAG, "execute: data=" + data.toString());
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
String token = null;
String senderID = null;
try {
jo = data.getJSONObject(0).getJSONObject(ANDROID);
Log.v(LOG_TAG, "execute: jo=" + jo.toString());
//senderID = jo.getString(SENDER_ID);
senderID = AlibabaSDK.getGlobalProperty(SdkConstants.APP_KEY);
Log.v(LOG_TAG, "execute: senderID=" + senderID);
String savedSenderID = sharedPref.getString(SENDER_ID, "");
String savedRegID = sharedPref.getString(REGISTRATION_ID, "");
/*
// first time run get new token
if ("".equals(savedRegID)) {
token = InstanceID.getInstance(getApplicationContext()).getToken(senderID, GCM);
}
// new sender ID, re-register
else if (!savedSenderID.equals(senderID)) {
token = InstanceID.getInstance(getApplicationContext()).getToken(senderID, GCM);
}
// use the saved one
else {
token = sharedPref.getString(REGISTRATION_ID, "");
}
*/
//使用aliyun push返回的设备号
token = PushServiceFactory.getCloudPushService().getDeviceId();
token = "aliyun:" + token;
if (!"".equals(token)) {
JSONObject json = new JSONObject().put(REGISTRATION_ID, token);
Log.v(LOG_TAG, "onRegistered: " + json.toString());
JSONArray topics = jo.optJSONArray(TOPICS);
subscribeToTopics(topics, token);
PushPlugin.sendEvent( json );
} else {
callbackContext.error("Empty registration ID received from GCM");
return;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
callbackContext.error(e.getMessage());
} catch (Exception e) {
Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
callbackContext.error(e.getMessage());
}
if (jo != null) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(ICON, jo.getString(ICON));
} catch (JSONException e) {
Log.d(LOG_TAG, "no icon option");
}
try {
editor.putString(ICON_COLOR, jo.getString(ICON_COLOR));
} catch (JSONException e) {
Log.d(LOG_TAG, "no iconColor option");
}
editor.putBoolean(SOUND, jo.optBoolean(SOUND, true));
editor.putBoolean(VIBRATE, jo.optBoolean(VIBRATE, true));
editor.putBoolean(CLEAR_NOTIFICATIONS, jo.optBoolean(CLEAR_NOTIFICATIONS, true));
editor.putBoolean(FORCE_SHOW, jo.optBoolean(FORCE_SHOW, false));
editor.putString(SENDER_ID, senderID);
editor.putString(REGISTRATION_ID, token);
editor.commit();
}
if (gCachedExtras != null) {
Log.v(LOG_TAG, "sending cached extras");
sendExtras(gCachedExtras);
gCachedExtras = null;
}
}
@Override
public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) {
Log.v(LOG_TAG, "execute: action=" + action);
gWebView = this.webView;
if (INITIALIZE.equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
//初始化阿里云SDK
initOneSDK(getApplicationContext(), data, callbackContext);
}
});
} else if (UNREGISTER.equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
String token = sharedPref.getString(REGISTRATION_ID, "");
JSONArray topics = data.optJSONArray(0);
if (topics != null && !"".equals(token)) {
unsubscribeFromTopics(topics, token);
} else {
InstanceID.getInstance(getApplicationContext()).deleteInstanceID();
Log.v(LOG_TAG, "UNREGISTER");
// Remove shared prefs
SharedPreferences.Editor editor = sharedPref.edit();
editor.remove(SOUND);
editor.remove(VIBRATE);
editor.remove(CLEAR_NOTIFICATIONS);
editor.remove(FORCE_SHOW);
editor.remove(SENDER_ID);
editor.remove(REGISTRATION_ID);
editor.commit();
}
callbackContext.success();
} catch (IOException e) {
Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
callbackContext.error(e.getMessage());
}
}
});
} else if (FINISH.equals(action)) {
callbackContext.success();
} else if (HAS_PERMISSION.equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
JSONObject jo = new JSONObject();
try {
jo.put("isEnabled", PermissionUtils.hasPermission(getApplicationContext(), "OP_POST_NOTIFICATION"));
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jo);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
} catch (UnknownError e) {
callbackContext.error(e.getMessage());
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
}
});
} else if (SET_APPLICATION_ICON_BADGE_NUMBER.equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Log.v(LOG_TAG, "setApplicationIconBadgeNumber: data=" + data.toString());
try {
setApplicationIconBadgeNumber(getApplicationContext(), data.getJSONObject(0).getInt(BADGE));
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
callbackContext.success();
}
});
} else if (CLEAR_ALL_NOTIFICATIONS.equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Log.v(LOG_TAG, "clearAllNotifications");
clearAllNotifications();
callbackContext.success();
}
});
} else {
Log.e(LOG_TAG, "Invalid action : " + action);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
return false;
}
return true;
}
public static void sendEvent(JSONObject _json) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, _json);
pluginResult.setKeepCallback(true);
if (pushContext != null) {
pushContext.sendPluginResult(pluginResult);
}
}
public static void sendError(String message) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, message);
pluginResult.setKeepCallback(true);
if (pushContext != null) {
pushContext.sendPluginResult(pluginResult);
}
}
/*
* Sends the pushbundle extras to the client application.
* If the client application isn't currently active, it is cached for later processing.
*/
public static void sendExtras(Bundle extras) {
if (extras != null) {
if (gWebView != null) {
sendEvent(convertBundleToJson(extras));
} else {
Log.v(LOG_TAG, "sendExtras: caching extras to send at a later time.");
gCachedExtras = extras;
}
}
}
public static void setApplicationIconBadgeNumber(Context context, int badgeCount) {
if (badgeCount > 0) {
ShortcutBadger.applyCount(context, badgeCount);
} else {
ShortcutBadger.removeCount(context);
}
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
gForeground = true;
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
gForeground = false;
SharedPreferences prefs = getApplicationContext().getSharedPreferences(COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
if (prefs.getBoolean(CLEAR_NOTIFICATIONS, true)) {
clearAllNotifications();
}
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
gForeground = true;
}
@Override
public void onDestroy() {
super.onDestroy();
gForeground = false;
gWebView = null;
}
private void clearAllNotifications() {
final NotificationManager notificationManager = (NotificationManager) cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
private void subscribeToTopics(JSONArray topics, String registrationToken) {
if (topics != null) {
String topic = null;
for (int i=0; i<topics.length(); i++) {
try {
topic = topics.optString(i, null);
if (topic != null) {
Log.d(LOG_TAG, "Subscribing to topic: " + topic);
GcmPubSub.getInstance(getApplicationContext()).subscribe(registrationToken, "/topics/" + topic, null);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to subscribe to topic: " + topic, e);
}
}
}
}
private void unsubscribeFromTopics(JSONArray topics, String registrationToken) {
if (topics != null) {
String topic = null;
for (int i=0; i<topics.length(); i++) {
try {
topic = topics.optString(i, null);
if (topic != null) {
Log.d(LOG_TAG, "Unsubscribing to topic: " + topic);
GcmPubSub.getInstance(getApplicationContext()).unsubscribe(registrationToken, "/topics/" + topic);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to unsubscribe to topic: " + topic, e);
}
}
}
}
/*
* serializes a bundle to JSON.
*/
private static JSONObject convertBundleToJson(Bundle extras) {
Log.d(LOG_TAG, "convert extras to json");
try {
JSONObject json = new JSONObject();
JSONObject additionalData = new JSONObject();
// Add any keys that need to be in top level json to this set
HashSet<String> jsonKeySet = new HashSet();
Collections.addAll(jsonKeySet, TITLE,MESSAGE,COUNT,SOUND,IMAGE);
Iterator<String> it = extras.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = extras.get(key);
Log.d(LOG_TAG, "key = " + key);
if (jsonKeySet.contains(key)) {
json.put(key, value);
}
else if (key.equals(COLDSTART)) {
additionalData.put(key, extras.getBoolean(COLDSTART));
}
else if (key.equals(FOREGROUND)) {
additionalData.put(key, extras.getBoolean(FOREGROUND));
}
else if ( value instanceof String ) {
String strValue = (String)value;
try {
// Try to figure out if the value is another JSON object
if (strValue.startsWith("{")) {
additionalData.put(key, new JSONObject(strValue));
}
// Try to figure out if the value is another JSON array
else if (strValue.startsWith("[")) {
additionalData.put(key, new JSONArray(strValue));
}
else {
additionalData.put(key, value);
}
} catch (Exception e) {
additionalData.put(key, value);
}
}
} // while
json.put(ADDITIONAL_DATA, additionalData);
Log.v(LOG_TAG, "extrasToJSON: " + json.toString());
return json;
}
catch( JSONException e) {
Log.e(LOG_TAG, "extrasToJSON: JSON exception");
}
return null;
}
public static boolean isInForeground() {
return gForeground;
}
public static boolean isActive() {
return gWebView != null;
}
}
|
/*
* Copyright 2013 LinkedIn Corp.
*
* 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 azkaban.executor;
import azkaban.flow.Flow;
import azkaban.project.Project;
import azkaban.sla.SlaOption;
import azkaban.utils.TypedMapWrapper;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class ExecutableFlow extends ExecutableFlowBase {
public static final String EXECUTIONID_PARAM = "executionId";
public static final String EXECUTIONPATH_PARAM = "executionPath";
public static final String EXECUTIONOPTIONS_PARAM = "executionOptions";
public static final String PROJECTID_PARAM = "projectId";
public static final String SCHEDULEID_PARAM = "scheduleId";
public static final String SUBMITUSER_PARAM = "submitUser";
public static final String SUBMITTIME_PARAM = "submitTime";
public static final String VERSION_PARAM = "version";
public static final String PROXYUSERS_PARAM = "proxyUsers";
public static final String PROJECTNAME_PARAM = "projectName";
public static final String LASTMODIFIEDTIME_PARAM = "lastModfiedTime";
public static final String LASTMODIFIEDUSER_PARAM = "lastModifiedUser";
public static final String SLAOPTIONS_PARAM = "slaOptions";
public static final String AZKABANFLOWVERSION_PARAM = "azkabanFlowVersion";
public static final String IS_LOCKED_PARAM = "isLocked";
private final HashSet<String> proxyUsers = new HashSet<>();
private int executionId = -1;
private int scheduleId = -1;
private int projectId;
private String projectName;
private String lastModifiedUser;
private int version;
private long submitTime = -1;
private long lastModifiedTimestamp;
private String submitUser;
private String executionPath;
private ExecutionOptions executionOptions;
private double azkabanFlowVersion;
private boolean isLocked;
public ExecutableFlow(final Project project, final Flow flow) {
this.projectId = project.getId();
this.projectName = project.getName();
this.version = project.getVersion();
this.scheduleId = -1;
this.lastModifiedTimestamp = project.getLastModifiedTimestamp();
this.lastModifiedUser = project.getLastModifiedUser();
setAzkabanFlowVersion(flow.getAzkabanFlowVersion());
setLocked(flow.isLocked());
this.setFlow(project, flow);
}
public ExecutableFlow() {
}
public static ExecutableFlow createExecutableFlowFromObject(final Object obj) {
final ExecutableFlow exFlow = new ExecutableFlow();
final HashMap<String, Object> flowObj = (HashMap<String, Object>) obj;
exFlow.fillExecutableFromMapObject(flowObj);
return exFlow;
}
@Override
public String getId() {
return getFlowId();
}
@Override
public ExecutableFlow getExecutableFlow() {
return this;
}
public void addAllProxyUsers(final Collection<String> proxyUsers) {
this.proxyUsers.addAll(proxyUsers);
}
public Set<String> getProxyUsers() {
return new HashSet<>(this.proxyUsers);
}
public ExecutionOptions getExecutionOptions() {
return this.executionOptions;
}
public void setExecutionOptions(final ExecutionOptions options) {
this.executionOptions = options;
}
@Override
protected void setFlow(final Project project, final Flow flow) {
super.setFlow(project, flow);
this.executionOptions = new ExecutionOptions();
this.executionOptions.setMailCreator(flow.getMailCreator());
if (flow.getSuccessEmails() != null) {
this.executionOptions.setSuccessEmails(flow.getSuccessEmails());
}
if (flow.getFailureEmails() != null) {
this.executionOptions.setFailureEmails(flow.getFailureEmails());
}
if (flow.getSuccessSms() != null) {
this.executionOptions.setSuccessSms(flow.getSuccessSms());
}
if (flow.getFailureSms() != null) {
this.executionOptions.setFailureSms(flow.getFailureSms());
}
}
@Override
public int getExecutionId() {
return this.executionId;
}
public void setExecutionId(final int executionId) {
this.executionId = executionId;
}
@Override
public long getLastModifiedTimestamp() {
return this.lastModifiedTimestamp;
}
public void setLastModifiedTimestamp(final long lastModifiedTimestamp) {
this.lastModifiedTimestamp = lastModifiedTimestamp;
}
@Override
public String getLastModifiedByUser() {
return this.lastModifiedUser;
}
public void setLastModifiedByUser(final String lastModifiedUser) {
this.lastModifiedUser = lastModifiedUser;
}
@Override
public int getProjectId() {
return this.projectId;
}
public void setProjectId(final int projectId) {
this.projectId = projectId;
}
@Override
public String getProjectName() {
return this.projectName;
}
public int getScheduleId() {
return this.scheduleId;
}
public void setScheduleId(final int scheduleId) {
this.scheduleId = scheduleId;
}
public String getExecutionPath() {
return this.executionPath;
}
public void setExecutionPath(final String executionPath) {
this.executionPath = executionPath;
}
public String getSubmitUser() {
return this.submitUser;
}
public void setSubmitUser(final String submitUser) {
this.submitUser = submitUser;
}
@Override
public int getVersion() {
return this.version;
}
public void setVersion(final int version) {
this.version = version;
}
public long getSubmitTime() {
return this.submitTime;
}
public void setSubmitTime(final long submitTime) {
this.submitTime = submitTime;
}
public double getAzkabanFlowVersion() {
return this.azkabanFlowVersion;
}
public void setAzkabanFlowVersion(final double azkabanFlowVersion) {
this.azkabanFlowVersion = azkabanFlowVersion;
}
public boolean isLocked() { return this.isLocked; }
public void setLocked(boolean locked) { this.isLocked = locked; }
@Override
public Map<String, Object> toObject() {
final HashMap<String, Object> flowObj = new HashMap<>();
fillMapFromExecutable(flowObj);
flowObj.put(EXECUTIONID_PARAM, this.executionId);
flowObj.put(EXECUTIONPATH_PARAM, this.executionPath);
flowObj.put(PROJECTID_PARAM, this.projectId);
flowObj.put(PROJECTNAME_PARAM, this.projectName);
if (this.scheduleId >= 0) {
flowObj.put(SCHEDULEID_PARAM, this.scheduleId);
}
flowObj.put(SUBMITUSER_PARAM, this.submitUser);
flowObj.put(VERSION_PARAM, this.version);
flowObj.put(LASTMODIFIEDTIME_PARAM, this.lastModifiedTimestamp);
flowObj.put(LASTMODIFIEDUSER_PARAM, this.lastModifiedUser);
flowObj.put(AZKABANFLOWVERSION_PARAM, this.azkabanFlowVersion);
flowObj.put(EXECUTIONOPTIONS_PARAM, this.executionOptions.toObject());
final ArrayList<String> proxyUserList = new ArrayList<>(this.proxyUsers);
flowObj.put(PROXYUSERS_PARAM, proxyUserList);
flowObj.put(SUBMITTIME_PARAM, this.submitTime);
final List<Map<String, Object>> slaOptions = new ArrayList<>();
this.executionOptions.getSlaOptions().stream()
.forEach((slaOption) -> slaOptions.add(slaOption.toObject()));
flowObj.put(SLAOPTIONS_PARAM, slaOptions);
flowObj.put(IS_LOCKED_PARAM, this.isLocked);
return flowObj;
}
@Override
public void fillExecutableFromMapObject(
final TypedMapWrapper<String, Object> flowObj) {
super.fillExecutableFromMapObject(flowObj);
this.executionId = flowObj.getInt(EXECUTIONID_PARAM);
this.executionPath = flowObj.getString(EXECUTIONPATH_PARAM);
this.projectId = flowObj.getInt(PROJECTID_PARAM);
this.projectName = flowObj.getString(PROJECTNAME_PARAM);
this.scheduleId = flowObj.getInt(SCHEDULEID_PARAM);
this.submitUser = flowObj.getString(SUBMITUSER_PARAM);
this.version = flowObj.getInt(VERSION_PARAM);
this.lastModifiedTimestamp = flowObj.getLong(LASTMODIFIEDTIME_PARAM);
this.lastModifiedUser = flowObj.getString(LASTMODIFIEDUSER_PARAM);
this.submitTime = flowObj.getLong(SUBMITTIME_PARAM);
this.azkabanFlowVersion = flowObj.getDouble(AZKABANFLOWVERSION_PARAM);
if (flowObj.containsKey(EXECUTIONOPTIONS_PARAM)) {
this.executionOptions =
ExecutionOptions.createFromObject(flowObj
.getObject(EXECUTIONOPTIONS_PARAM));
} else {
// for backwards compatibility should remove in a few versions.
this.executionOptions = ExecutionOptions.createFromObject(flowObj);
}
if (flowObj.containsKey(PROXYUSERS_PARAM)) {
final List<String> proxyUserList = flowObj.<String>getList(PROXYUSERS_PARAM);
this.addAllProxyUsers(proxyUserList);
}
if (flowObj.containsKey(SLAOPTIONS_PARAM)) {
final List<SlaOption> slaOptions =
flowObj.getList(SLAOPTIONS_PARAM).stream().map(SlaOption::fromObject)
.collect(Collectors.toList());
this.executionOptions.setSlaOptions(slaOptions);
}
this.setLocked(flowObj.getBool(IS_LOCKED_PARAM, false));
}
@Override
public Map<String, Object> toUpdateObject(final long lastUpdateTime) {
final Map<String, Object> updateData = super.toUpdateObject(lastUpdateTime);
updateData.put(EXECUTIONID_PARAM, this.executionId);
return updateData;
}
@Override
public void resetForRetry() {
super.resetForRetry();
this.setStatus(Status.RUNNING);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.network;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The AzureFirewallNatRule model. */
@Fluent
public final class AzureFirewallNatRule {
/*
* Name of the NAT rule.
*/
@JsonProperty(value = "name")
private String name;
/*
* Description of the rule.
*/
@JsonProperty(value = "description")
private String description;
/*
* List of source IP addresses for this rule.
*/
@JsonProperty(value = "sourceAddresses")
private List<String> sourceAddresses;
/*
* List of destination IP addresses for this rule. Supports IP ranges,
* prefixes, and service tags.
*/
@JsonProperty(value = "destinationAddresses")
private List<String> destinationAddresses;
/*
* List of destination ports.
*/
@JsonProperty(value = "destinationPorts")
private List<String> destinationPorts;
/*
* Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
*/
@JsonProperty(value = "protocols")
private List<AzureFirewallNetworkRuleProtocol> protocols;
/*
* The translated address for this NAT rule.
*/
@JsonProperty(value = "translatedAddress")
private String translatedAddress;
/*
* The translated port for this NAT rule.
*/
@JsonProperty(value = "translatedPort")
private String translatedPort;
/**
* Get the name property: Name of the NAT rule.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Set the name property: Name of the NAT rule.
*
* @param name the name value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withName(String name) {
this.name = name;
return this;
}
/**
* Get the description property: Description of the rule.
*
* @return the description value.
*/
public String description() {
return this.description;
}
/**
* Set the description property: Description of the rule.
*
* @param description the description value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withDescription(String description) {
this.description = description;
return this;
}
/**
* Get the sourceAddresses property: List of source IP addresses for this rule.
*
* @return the sourceAddresses value.
*/
public List<String> sourceAddresses() {
return this.sourceAddresses;
}
/**
* Set the sourceAddresses property: List of source IP addresses for this rule.
*
* @param sourceAddresses the sourceAddresses value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withSourceAddresses(List<String> sourceAddresses) {
this.sourceAddresses = sourceAddresses;
return this;
}
/**
* Get the destinationAddresses property: List of destination IP addresses for this rule. Supports IP ranges,
* prefixes, and service tags.
*
* @return the destinationAddresses value.
*/
public List<String> destinationAddresses() {
return this.destinationAddresses;
}
/**
* Set the destinationAddresses property: List of destination IP addresses for this rule. Supports IP ranges,
* prefixes, and service tags.
*
* @param destinationAddresses the destinationAddresses value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withDestinationAddresses(List<String> destinationAddresses) {
this.destinationAddresses = destinationAddresses;
return this;
}
/**
* Get the destinationPorts property: List of destination ports.
*
* @return the destinationPorts value.
*/
public List<String> destinationPorts() {
return this.destinationPorts;
}
/**
* Set the destinationPorts property: List of destination ports.
*
* @param destinationPorts the destinationPorts value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withDestinationPorts(List<String> destinationPorts) {
this.destinationPorts = destinationPorts;
return this;
}
/**
* Get the protocols property: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
*
* @return the protocols value.
*/
public List<AzureFirewallNetworkRuleProtocol> protocols() {
return this.protocols;
}
/**
* Set the protocols property: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
*
* @param protocols the protocols value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withProtocols(List<AzureFirewallNetworkRuleProtocol> protocols) {
this.protocols = protocols;
return this;
}
/**
* Get the translatedAddress property: The translated address for this NAT rule.
*
* @return the translatedAddress value.
*/
public String translatedAddress() {
return this.translatedAddress;
}
/**
* Set the translatedAddress property: The translated address for this NAT rule.
*
* @param translatedAddress the translatedAddress value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withTranslatedAddress(String translatedAddress) {
this.translatedAddress = translatedAddress;
return this;
}
/**
* Get the translatedPort property: The translated port for this NAT rule.
*
* @return the translatedPort value.
*/
public String translatedPort() {
return this.translatedPort;
}
/**
* Set the translatedPort property: The translated port for this NAT rule.
*
* @param translatedPort the translatedPort value to set.
* @return the AzureFirewallNatRule object itself.
*/
public AzureFirewallNatRule withTranslatedPort(String translatedPort) {
this.translatedPort = translatedPort;
return this;
}
}
|
package com.handmobile.cordova.hotpatch;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import org.apache.cordova.CordovaWebView;
import android.R.bool;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.widget.TextView;
import android.content.SharedPreferences; // add by ciwei
import android.preference.PreferenceManager; // add by ciwei
import android.content.pm.PackageManager;// add by ciwei
import android.content.res.Resources;
import android.content.pm.PackageInfo;// add by ciwei
import android.util.Log;
public class DownLoadTask extends AsyncTask<String, String, Boolean>{
private final static int TIME_OUT = 30 * 1000;
private String patchAppVersionKey ="patchAppVersion";
private Context mContext;
private CordovaWebView mWebView;
private ProgressDialog mProgressDialog;
private MyProgressBar mProgressBar;
private TextView mPercent;
private String mPercentString;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mPercent.setText(mPercentString);
}
};
public DownLoadTask(Context context,CordovaWebView webView)
{
mContext = context;
mWebView = webView;
mProgressDialog = new ProgressDialog(mContext);
// mProgressDialog.setTitle("升级文件下载");
// mProgressDialog.setMessage("文件下载中,请稍候...");
// mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgress(0);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
mProgressDialog.setOnKeyListener(onKeyListener);
mProgressDialog.setContentView(getResId("alterlayout"));
mProgressBar = (MyProgressBar) mProgressDialog.findViewById(getId("progressBar1"));
mProgressBar.setProgress(0);
mPercent =(TextView)mProgressDialog.findViewById(getId("tv_percent"));
}
@Override
protected Boolean doInBackground(String... params) {
if(params[0] !=null){
String url = params[0];
try {
HttpURLConnection connection = null;
URL u = new URL(url);
connection = (HttpURLConnection) u.openConnection();
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setConnectTimeout(TIME_OUT);
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
mContext.deleteFile("www.zip");
OutputStream output = mContext.openFileOutput("www.zip", Context.MODE_PRIVATE);
byte data[] = new byte[1024 * 20];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
publishProgress(String.valueOf((total * 100) / lenghtOfFile));
}
output.flush();
output.close();
input.close();
mContext.deleteFile("www");
ZipUtil.UnZipFolder(mContext.getFileStreamPath("www.zip").toString(), mContext.getFilesDir().toString().concat("/"));
//保存版本号
SharedPreferences mSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = mSharedPreferences.edit();
PackageManager packageManager = mContext.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
mContext.getPackageName(), 0);// mod by ciwei +m
String currentVersion = packageInfo.versionName;
editor.putString(patchAppVersionKey,currentVersion);
editor.commit();
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}else {
return false;
}
return true;
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
mProgressDialog.setProgress(Integer.parseInt(values[0]));
mProgressBar.setProgress(Integer.parseInt(values[0]));
mPercentString =values[0]+"%";
mHandler.sendEmptyMessage(100);
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if(true){
new Handler().postDelayed(new Runnable() {
public void run() {
mWebView.clearHistory();
mWebView.clearCache();
}
}, 0);
mWebView.loadUrlIntoView("file://".concat(mContext.getFilesDir().getPath()).concat("/www/index.html"), false);
}
else {
}
}
///////////////////
private OnKeyListener onKeyListener = new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
mProgressDialog.dismiss();
}
return false;
}
};
///////////////////////add by fuwei/////////////////////////////////
private int getResId(String resourceName){
Resources resources = mContext.getResources();
int resId = resources.getIdentifier(resourceName,"layout",mContext.getPackageName());
// int resId = resources.getIdentifier(getPackageName() + ":layout/" + resourceName, null, null);
return resId;
}
private int getId(String idName){
Resources resources = mContext.getResources();
int resId = resources.getIdentifier(idName, "id", mContext.getPackageName());
return resId;
}
//////////////////////////////////////////////////////////
}
|
/**
* Copyright (C) 2016 Red Hat, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.fabric8.jenkins.openshiftsync.systest;
import com.offbytwo.jenkins.model.Build;
import com.offbytwo.jenkins.model.BuildWithDetails;
import com.offbytwo.jenkins.model.JobWithDetails;
import com.offbytwo.jenkins.model.QueueReference;
import io.fabric8.jenkins.openshiftsync.systest.support.JenkinsConfigXmlAssertions;
import io.fabric8.jenkins.openshiftsync.systest.support.JobDeleteKind;
import io.fabric8.jenkins.openshiftsync.systest.support.OpenShiftTestUtils;
import io.fabric8.jenkins.openshiftsync.systest.support.SystemProperties;
import io.fabric8.testing.jenkins.JenkinsAsserts;
import io.fabric8.utils.DomHelper;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import javax.xml.transform.TransformerException;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import static io.fabric8.jenkins.openshiftsync.systest.support.JenkinsConfigXmlAssertions.assertHasGithubNavigatorPattern;
import static io.fabric8.testing.jenkins.JenkinsAsserts.assertTriggerJobPath;
import static io.fabric8.testing.jenkins.JenkinsAsserts.assertWaitForNoRunningBuilds;
import static net.sf.ezmorph.test.ArrayAssertions.assertEquals;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertTrue;
/**
* A system test to run on the current available openshift/kubernetes cluster
* against the jenkins service pointed to via the kubernetes style environment variables.
* <br>
* Uses <code>KUBERNETES_NAMESPACE</code> as the namespace to use and <code></code>
*/
public class SyncIT extends Clear {
private static final transient Logger LOG = LoggerFactory.getLogger(SyncIT.class);
protected String githubOrgJobName = "jstrachan";
protected String bcName1 = "cheese140";
protected String bcName2 = "cheese142";
protected String bcName3 = "cheese149";
protected String branchName = "master";
protected long waitForBuildTimeout = 100000L;
protected long waitForBuildConfigDeleteTimeout = 20000L;
public static void assertJobNotInOrganisationPattern(Document doc, String orgJob, String jobName, String description) {
String pattern = assertHasGithubNavigatorPattern(doc, description);
LOG.info("Found github organisation pattern: " + pattern);
Set<String> patterns = JenkinsConfigXmlAssertions.patternSet(pattern);
assertTrue("Should not contain " + jobName + " in the github org pattern set " + patterns, !patterns.contains(jobName));
}
public static void assertJobsInOrganisationPattern(Document doc, String[] jobNames, String description) {
String pattern = assertHasGithubNavigatorPattern(doc, description);
LOG.info("Found github organisation pattern: " + pattern);
Set<String> patterns = JenkinsConfigXmlAssertions.patternSet(pattern);
for (String jobName : jobNames) {
assertTrue("Should contain " + jobName + " in the github org pattern set " + patterns, patterns.contains(jobName));
}
}
@Before
public void init() throws Exception {
super.init();
String basedir = System.getProperty("basedir", ".");
File sysTestResourceDir = new File(basedir, "src/test/resources/systest");
assertTrue("Folder " + sysTestResourceDir + " is not a directory!", sysTestResourceDir.exists() && sysTestResourceDir.isDirectory());
LOG.info("Applying resource to namespace " + namespace);
int resourceCount = OpenShiftTestUtils.applyResources(openShiftClient, namespace, sysTestResourceDir);
assertTrue("Should have found at least one resource", resourceCount > 0);
JenkinsAsserts.assertWaitForJobPathExists(jenkins, waitForBuildTimeout, githubOrgJobName, bcName1, branchName);
JenkinsAsserts.assertWaitForJobPathExists(jenkins, waitForBuildTimeout, githubOrgJobName, bcName2, branchName);
JenkinsAsserts.assertWaitForJobPathExists(jenkins, waitForBuildTimeout, githubOrgJobName, bcName3, branchName);
assertJobsInOrganisationPattern(githubOrgJobName, bcName1, bcName2, bcName3);
displayJobs();
displayBuildConfigs();
}
@Test
public void testRun() throws Exception {
assertWaitForNoRunningBuilds(jenkins, waitForBuildTimeout);
waitForTestToStart();
LOG.info("Lets delete BuildConfigs while jenkins is up");
String job1lastBuildID = assertGetLastBuildID(bcName1);
String job3lastBuildID = assertGetLastBuildID(bcName3);
String bcName = bcName2;
deleteBuildConfig(bcName);
assertBuildNotExist(bcName);
assertBuildsExist(bcName1, bcName3);
displayBuildConfigs();
displayJobs();
assertLastBuildID(bcName1, job1lastBuildID);
assertLastBuildID(bcName3, job3lastBuildID);
LOG.info("Lets trigger an Organisation Scan");
QueueReference queueReference = assertTriggerJobPath(jenkins, githubOrgJobName);
assertWaitForNoRunningBuilds(jenkins, waitForBuildTimeout);
assertLastBuildID(bcName1, job1lastBuildID);
assertLastBuildID(bcName3, job3lastBuildID);
bcName = bcName1;
deletePatternFromOrganisationJob(bcName);
assertBuildNotExist(bcName);
assertBuildsExist(bcName3);
displayBuildConfigs();
displayJobs();
assertLastBuildID(bcName3, job3lastBuildID);
bcName = bcName3;
deletePatternFromOrganisationJob(bcName);
assertBuildNotExist(bcName);
displayBuildConfigs();
displayJobs();
}
public void deleteJobWithKind(String bcName) {
JobDeleteKind deleteKind = JobDeleteKind.getValue();
LOG.info("Deleting job " + bcName + " using strategy: " + deleteKind);
switch (deleteKind) {
case DeleteBuildConfig:
deleteBuildConfig(bcName);
return;
case DeletePatternFromConfigMapJob:
deletePatternFromConfigMapJob(bcName);
return;
case DeletePatternFromOrganisationJob:
deletePatternFromOrganisationJob(bcName);
return;
default:
fail("Unknown Delete kind: " + deleteKind);
}
}
protected void assertLastBuildID(String buildName, String expectedBuildID) throws IOException {
String id = assertGetLastBuildID(buildName);
assertEquals("Job " + buildName + " last build ID", expectedBuildID, id);
}
public String assertGetLastBuildID(String buildName) throws IOException {
JobWithDetails jobDetails = JenkinsAsserts.assertJobPathExists(jenkins, githubOrgJobName, buildName, branchName);
Build lastBuild = jobDetails.getLastBuild();
assertTrue("Job " + buildName + " should have a last build!", lastBuild != null);
BuildWithDetails details = lastBuild.details();
assertTrue("Job " + buildName + " last build should have have details!", details != null);
return details.getId();
}
protected void waitForTestToStart() {
if (SystemProperties.isPropertyFlag(SystemProperties.WAIT_FOR_USER_PROMPT)) {
System.out.println();
System.out.println("Press [ENTER] to continue the test:");
Console c = System.console();
c.readLine();
} else {
doSleep(2000);
}
}
public void assertBuildNotExist(String bcName) throws Exception {
JenkinsAsserts.assertWaitForJobPathNotExist(jenkins, waitForBuildTimeout, githubOrgJobName, bcName, "master");
assertJobNotInOrganisationPattern(githubOrgJobName, bcName);
JenkinsAsserts.assertWaitForJobPathNotExist(jenkins, waitForBuildTimeout, githubOrgJobName, bcName);
OpenShiftTestUtils.assertWaitForBuildConfigNotExist(openShiftClient, namespace, bcName, waitForBuildConfigDeleteTimeout);
}
protected void assertBuildsExist(String... buildNames) throws IOException {
for (String buildName : buildNames) {
JenkinsAsserts.assertJobPathExists(jenkins, githubOrgJobName, buildName, branchName);
OpenShiftTestUtils.assertBuildConfigExists(openShiftClient, namespace, buildName);
}
}
protected void deletePatternFromOrganisationJob(String bcName) {
LOG.info("Deleting Job " + bcName + " by updating the pattern in Organisation Job " + githubOrgJobName);
Document doc = JenkinsAsserts.assertJobXmlDocument(jenkins, githubOrgJobName);
JenkinsConfigXmlAssertions.assertRemovePattern(doc, bcName, "Org Job config.xml for " + githubOrgJobName);
assertUpdateJob(bcName, doc);
}
protected void deletePatternFromConfigMapJob(String bcName) {
LOG.info("Deleting Job " + bcName + " by updating the pattern in the ConfigMap Organisation Job " + githubOrgJobName);
Document doc = OpenShiftTestUtils.assertConfigXmlFromConfigMapJob(openShiftClient, namespace, githubOrgJobName);
JenkinsConfigXmlAssertions.assertRemovePattern(doc, bcName, "ConfigMap " + githubOrgJobName + " config.xml");
String xml = assertToXml(doc, "config.xml for job " + bcName);
OpenShiftTestUtils.assertUpdateConfigMapDataKey(openShiftClient, namespace, githubOrgJobName, "config.xml", xml);
}
protected void assertUpdateJob(String jobName, Document doc) {
String xml = assertToXml(doc, "config.xml for job " + jobName);
try {
jenkins.updateJob(githubOrgJobName, xml);
} catch (IOException e) {
throw new AssertionError("Failed to update XML of job " + jobName + " due to " + e, e);
}
}
private String assertToXml(Document doc, String description) {
try {
return DomHelper.toXml(doc);
} catch (TransformerException e) {
throw new AssertionError("Failed to convert " + description + " to XML due to " + e, e);
}
}
public void assertJobsInOrganisationPattern(String orgJob, String... jobNames) {
Document doc = JenkinsAsserts.assertJobXmlDocument(jenkins, orgJob);
assertJobsInOrganisationPattern(doc, jobNames, "job XML for " + orgJob);
doc = OpenShiftTestUtils.assertConfigXmlFromConfigMapJob(openShiftClient, namespace, orgJob);
assertJobsInOrganisationPattern(doc, jobNames, "config.xml from ConfigMap job " + orgJob + " in namespace " + namespace);
}
public void assertJobNotInOrganisationPattern(String orgJob, String jobName) {
Document doc = JenkinsAsserts.assertJobXmlDocument(jenkins, orgJob);
assertJobNotInOrganisationPattern(doc, orgJob, jobName, "job XML for " + orgJob);
doc = OpenShiftTestUtils.assertConfigXmlFromConfigMapJob(openShiftClient, namespace, orgJob);
assertJobNotInOrganisationPattern(doc, orgJob, jobName, "config.xml from ConfigMap job " + orgJob + " in namespace " + namespace);
}
}
|
/**
* Copyright © 2016-2018 The Thingsboard Authors
* Modifications © 2017-2018 Hashmap, 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.hashmapinc.server.dao.theme;
import com.hashmapinc.server.dao.theme.ThemeDao;
import com.hashmapinc.server.common.data.Theme;
import com.hashmapinc.server.dao.entity.AbstractEntityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class ThemeServiceImpl extends AbstractEntityService implements ThemeService {
@Autowired
private ThemeDao themeDao;
@Override
public List<Theme> findAll() {
return themeDao.find();
}
@Override
public Theme findEnabledTheme() {
return themeDao.findEnabledTheme();
}
@Override
public Theme updateThemeStatus(String value) {
Theme theme = findEnabledTheme();
if(theme != null) {
theme.setThemeStatus(false);
themeDao.save(theme);
Theme themeNew = themeDao.findByValue(value);
if(themeNew != null) {
themeNew.setThemeStatus(true);
return themeDao.save(themeNew);
}
}
return null;
}
@Override
public Theme saveTheme(Theme theme) {
Theme themeNew = themeDao.save(theme);
if(themeNew != null) {
return themeNew;
}
return null;
}
@Override
public void deleteThemeEntryByvalue (String value) {
Theme theme = themeDao.findByValue(value);
if (theme != null) {
themeDao.removeById(theme.getUuidId());
}
}
}
|
package uk.gov.dft.bluebadge.service.badgemanagement.converter;
import static uk.gov.dft.bluebadge.service.badgemanagement.BadgeTestFixture.getValidOrgBadgeEntity;
import static uk.gov.dft.bluebadge.service.badgemanagement.BadgeTestFixture.getValidPersonBadgeEntity;
import org.junit.Assert;
import org.junit.Test;
import uk.gov.dft.bluebadge.model.badgemanagement.generated.Badge;
import uk.gov.dft.bluebadge.service.badgemanagement.BadgeTestFixture;
import uk.gov.dft.bluebadge.service.badgemanagement.repository.domain.BadgeEntity;
public class BadgeConverterTest {
@Test
public void convertToModel_person() {
// Given a valid person badge
BadgeEntity entity = getValidPersonBadgeEntity();
// When converted to model
Badge model = new BadgeConverter().convertToModel(entity);
// Then person data is present but not organisation
Assert.assertEquals(entity.getHolderName(), model.getParty().getPerson().getBadgeHolderName());
Assert.assertNull(model.getParty().getOrganisation());
// And contact details present.
Assert.assertEquals(
model.getParty().getContact().getPrimaryPhoneNumber(), entity.getPrimaryPhoneNo());
Assert.assertEquals(BadgeTestFixture.DefaultVals.REPLACE_REASON, model.getReplaceReasonCode());
Assert.assertEquals(entity.getNotForReassessment(), model.getNotForReassessment());
}
@Test
public void convertToModel_org() {
// Given a valid person badge
BadgeEntity entity = getValidOrgBadgeEntity();
// When converted to model
Badge model = new BadgeConverter().convertToModel(entity);
// Then person data is present but not organisation
Assert.assertEquals(
entity.getHolderName(), model.getParty().getOrganisation().getBadgeHolderName());
Assert.assertNull(model.getParty().getPerson());
// And contact details present.
Assert.assertEquals(
entity.getPrimaryPhoneNo(), model.getParty().getContact().getPrimaryPhoneNumber());
Assert.assertEquals(entity.getNotForReassessment(), model.getNotForReassessment());
}
}
|
package fr.uem.efluid.generation;
import fr.uem.efluid.model.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <p>
* Holder of content for a generated dictionary,
* extracted from package def, annotation and all rules for API generation
* </p>
*
* @author elecomte
* @version 1
* @since v2.0.0
*/
public class DictionaryContent {
private final Collection<ParameterProjectDefinition> allProjects;
private final Collection<ParameterDomainDefinition> allDomains;
private final Collection<ParameterTableDefinition> allTables;
private final Collection<ParameterLinkDefinition> allLinks;
private final Collection<ParameterMappingDefinition> allMappings;
private final Collection<ParameterVersionDefinition> allVersions;
DictionaryContent(
Map<String, ParameterProjectDefinition> projectDefs,
Collection<ParameterDomainDefinition> allDomains,
Map<Class<?>, List<ParameterTableDefinition>> typeTables,
Collection<ParameterLinkDefinition> allLinks,
Collection<ParameterMappingDefinition> allMappings,
Collection<ParameterVersionDefinition> allVersions) {
// Remove the projects not used in domains
this.allProjects = projectDefs.values().stream()
.filter(p -> allDomains.stream().anyMatch(d -> d.getProject().getUuid().equals(p.getUuid())))
.collect(Collectors.toList());
this.allDomains = allDomains;
this.allTables = typeTables.values().stream()
.distinct()
.flatMap(Collection::stream)
.collect(Collectors.toList());
this.allLinks = allLinks;
this.allMappings = allMappings;
// Keep only versions used in filtered projects
this.allVersions = allVersions.stream()
.filter(v -> this.allProjects.stream().anyMatch(p -> p.getUuid().equals(v.getProject().getUuid())))
.collect(Collectors.toList());
}
public Collection<ParameterProjectDefinition> getAllProjects() {
return allProjects;
}
public Collection<ParameterDomainDefinition> getAllDomains() {
return allDomains;
}
public Collection<ParameterTableDefinition> getAllTables() {
return allTables;
}
public Collection<ParameterLinkDefinition> getAllLinks() {
return allLinks;
}
public Collection<ParameterMappingDefinition> getAllMappings() {
return allMappings;
}
public Collection<ParameterVersionDefinition> getAllVersions() {
return allVersions;
}
}
|
/****************************************************************
* 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.jspf.terms;
import org.apache.james.jspf.core.DNSLookupContinuation;
import org.apache.james.jspf.core.SPF1Constants;
import org.apache.james.jspf.core.SPFChecker;
import org.apache.james.jspf.core.SPFSession;
import org.apache.james.jspf.core.exceptions.NeutralException;
import org.apache.james.jspf.core.exceptions.NoneException;
import org.apache.james.jspf.core.exceptions.PermErrorException;
import org.apache.james.jspf.core.exceptions.TempErrorException;
import org.apache.james.jspf.executor.FutureSPFResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Directive is a mechanism with a resulting qualifier.
*/
public class Directive implements SPFChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(Directive.class);
private final class MechanismResultChecker implements SPFChecker {
/**
* @see org.apache.james.jspf.core.SPFChecker#checkSPF(org.apache.james.jspf.core.SPFSession)
*/
public DNSLookupContinuation checkSPF(SPFSession spfData)
throws PermErrorException, TempErrorException,
NeutralException, NoneException {
Boolean res = (Boolean) spfData.getAttribute(ATTRIBUTE_MECHANISM_RESULT);
if (res != null ? res.booleanValue() : true) {
if (qualifier.equals("")) {
spfData.setCurrentResult(SPF1Constants.PASS);
} else {
spfData.setCurrentResult(qualifier);
}
LOGGER.info("Processed directive matched: {} returned {}", Directive.this, spfData.getCurrentResult());
} else {
LOGGER.debug("Processed directive NOT matched: {}", this);
}
return null;
}
}
public static final String ATTRIBUTE_MECHANISM_RESULT = "Mechanism.result";
protected String qualifier = "+";
private Mechanism mechanism = null;
private MechanismResultChecker resultChecker;
/**
* Construct Directive
*
* @param qualifier The qualifier to use. Valid qualifier are: +, -, ~, ?
* @param mechanism The Mechanism
* @throws PermErrorException Get thrown if a PermError should returned
*/
public Directive(String qualifier, Mechanism mechanism)
throws PermErrorException {
super();
if (qualifier == null) {
throw new PermErrorException("Qualifier cannot be null");
}
this.qualifier = qualifier;
if (mechanism == null) {
throw new PermErrorException("Mechanism cannot be null");
}
this.resultChecker = new MechanismResultChecker();
this.mechanism = mechanism;
}
/**
* Run the Directive
*
* @param spfSession The SPFSession to use
* @return The qualifier which was returned
* @throws PermErrorException get thrown if a PermError should returned
* @throws TempErrorException get thrown if a TempError should returned
* @throws NoneException get thrown if a NoneException should returned;
* @throws NeutralException
*/
public DNSLookupContinuation checkSPF(SPFSession spfSession) throws PermErrorException,
TempErrorException, NoneException, NeutralException {
// if already have a current result we don't run this
if (spfSession.getCurrentResult() == null && spfSession.getCurrentResultExpanded() == null) {
spfSession.removeAttribute(ATTRIBUTE_MECHANISM_RESULT);
spfSession.pushChecker(resultChecker);
spfSession.pushChecker(mechanism);
}
return null;
}
/**
* Return the Mechanism which should be run
*
* @return the Mechanism
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* Return the Qualifier
*
* @return the qualifier
*/
public String getQualifier() {
return qualifier;
}
public String toString() {
return qualifier + mechanism;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: table.proto
package org.cddb.lsmt.internal;
public final class TableSerializer {
private TableSerializer() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface PointerOrBuilder extends
// @@protoc_insertion_point(interface_extends:Pointer)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string key = 1;</code>
*/
java.lang.String getKey();
/**
* <code>string key = 1;</code>
*/
com.google.protobuf.ByteString
getKeyBytes();
/**
* <code>int32 offset = 2;</code>
*/
int getOffset();
/**
* <code>int32 length = 3;</code>
*/
int getLength();
}
/**
* Protobuf type {@code Pointer}
*/
public static final class Pointer extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:Pointer)
PointerOrBuilder {
// Use Pointer.newBuilder() to construct.
private Pointer(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Pointer() {
key_ = "";
offset_ = 0;
length_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Pointer(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
key_ = s;
break;
}
case 16: {
offset_ = input.readInt32();
break;
}
case 24: {
length_ = input.readInt32();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Pointer_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Pointer_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Pointer.class, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder.class);
}
public static final int KEY_FIELD_NUMBER = 1;
private volatile java.lang.Object key_;
/**
* <code>string key = 1;</code>
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
}
}
/**
* <code>string key = 1;</code>
*/
public com.google.protobuf.ByteString
getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OFFSET_FIELD_NUMBER = 2;
private int offset_;
/**
* <code>int32 offset = 2;</code>
*/
public int getOffset() {
return offset_;
}
public static final int LENGTH_FIELD_NUMBER = 3;
private int length_;
/**
* <code>int32 length = 3;</code>
*/
public int getLength() {
return length_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getKeyBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, key_);
}
if (offset_ != 0) {
output.writeInt32(2, offset_);
}
if (length_ != 0) {
output.writeInt32(3, length_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getKeyBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, key_);
}
if (offset_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, offset_);
}
if (length_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(3, length_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.Pointer)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.Pointer other = (org.cddb.lsmt.internal.TableSerializer.Pointer) obj;
boolean result = true;
result = result && getKey()
.equals(other.getKey());
result = result && (getOffset()
== other.getOffset());
result = result && (getLength()
== other.getLength());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
hash = (37 * hash) + OFFSET_FIELD_NUMBER;
hash = (53 * hash) + getOffset();
hash = (37 * hash) + LENGTH_FIELD_NUMBER;
hash = (53 * hash) + getLength();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.Pointer prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Pointer}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Pointer)
org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Pointer_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Pointer_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Pointer.class, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.Pointer.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
key_ = "";
offset_ = 0;
length_ = 0;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Pointer_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.Pointer getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.Pointer.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.Pointer build() {
org.cddb.lsmt.internal.TableSerializer.Pointer result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.Pointer buildPartial() {
org.cddb.lsmt.internal.TableSerializer.Pointer result = new org.cddb.lsmt.internal.TableSerializer.Pointer(this);
result.key_ = key_;
result.offset_ = offset_;
result.length_ = length_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.Pointer) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.Pointer)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.Pointer other) {
if (other == org.cddb.lsmt.internal.TableSerializer.Pointer.getDefaultInstance()) return this;
if (!other.getKey().isEmpty()) {
key_ = other.key_;
onChanged();
}
if (other.getOffset() != 0) {
setOffset(other.getOffset());
}
if (other.getLength() != 0) {
setLength(other.getLength());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.Pointer parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.Pointer) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object key_ = "";
/**
* <code>string key = 1;</code>
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string key = 1;</code>
*/
public com.google.protobuf.ByteString
getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string key = 1;</code>
*/
public Builder setKey(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
onChanged();
return this;
}
/**
* <code>string key = 1;</code>
*/
public Builder clearKey() {
key_ = getDefaultInstance().getKey();
onChanged();
return this;
}
/**
* <code>string key = 1;</code>
*/
public Builder setKeyBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
key_ = value;
onChanged();
return this;
}
private int offset_ ;
/**
* <code>int32 offset = 2;</code>
*/
public int getOffset() {
return offset_;
}
/**
* <code>int32 offset = 2;</code>
*/
public Builder setOffset(int value) {
offset_ = value;
onChanged();
return this;
}
/**
* <code>int32 offset = 2;</code>
*/
public Builder clearOffset() {
offset_ = 0;
onChanged();
return this;
}
private int length_ ;
/**
* <code>int32 length = 3;</code>
*/
public int getLength() {
return length_;
}
/**
* <code>int32 length = 3;</code>
*/
public Builder setLength(int value) {
length_ = value;
onChanged();
return this;
}
/**
* <code>int32 length = 3;</code>
*/
public Builder clearLength() {
length_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:Pointer)
}
// @@protoc_insertion_point(class_scope:Pointer)
private static final org.cddb.lsmt.internal.TableSerializer.Pointer DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.Pointer();
}
public static org.cddb.lsmt.internal.TableSerializer.Pointer getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Pointer>
PARSER = new com.google.protobuf.AbstractParser<Pointer>() {
public Pointer parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Pointer(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Pointer> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Pointer> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.Pointer getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface SSTableIndexOrBuilder extends
// @@protoc_insertion_point(interface_extends:SSTableIndex)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .Pointer records = 3;</code>
*/
java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer>
getRecordsList();
/**
* <code>repeated .Pointer records = 3;</code>
*/
org.cddb.lsmt.internal.TableSerializer.Pointer getRecords(int index);
/**
* <code>repeated .Pointer records = 3;</code>
*/
int getRecordsCount();
/**
* <code>repeated .Pointer records = 3;</code>
*/
java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder>
getRecordsOrBuilderList();
/**
* <code>repeated .Pointer records = 3;</code>
*/
org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder getRecordsOrBuilder(
int index);
}
/**
* Protobuf type {@code SSTableIndex}
*/
public static final class SSTableIndex extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:SSTableIndex)
SSTableIndexOrBuilder {
// Use SSTableIndex.newBuilder() to construct.
private SSTableIndex(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SSTableIndex() {
records_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private SSTableIndex(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 26: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
records_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Pointer>();
mutable_bitField0_ |= 0x00000001;
}
records_.add(
input.readMessage(org.cddb.lsmt.internal.TableSerializer.Pointer.parser(), extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
records_ = java.util.Collections.unmodifiableList(records_);
}
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTableIndex_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTableIndex_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.class, org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder.class);
}
public static final int RECORDS_FIELD_NUMBER = 3;
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer> records_;
/**
* <code>repeated .Pointer records = 3;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer> getRecordsList() {
return records_;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder>
getRecordsOrBuilderList() {
return records_;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public int getRecordsCount() {
return records_.size();
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Pointer getRecords(int index) {
return records_.get(index);
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder getRecordsOrBuilder(
int index) {
return records_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < records_.size(); i++) {
output.writeMessage(3, records_.get(i));
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < records_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, records_.get(i));
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.SSTableIndex)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.SSTableIndex other = (org.cddb.lsmt.internal.TableSerializer.SSTableIndex) obj;
boolean result = true;
result = result && getRecordsList()
.equals(other.getRecordsList());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getRecordsCount() > 0) {
hash = (37 * hash) + RECORDS_FIELD_NUMBER;
hash = (53 * hash) + getRecordsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.SSTableIndex prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code SSTableIndex}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:SSTableIndex)
org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTableIndex_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTableIndex_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.class, org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.SSTableIndex.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getRecordsFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (recordsBuilder_ == null) {
records_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
recordsBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTableIndex_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.SSTableIndex.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex build() {
org.cddb.lsmt.internal.TableSerializer.SSTableIndex result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex buildPartial() {
org.cddb.lsmt.internal.TableSerializer.SSTableIndex result = new org.cddb.lsmt.internal.TableSerializer.SSTableIndex(this);
int from_bitField0_ = bitField0_;
if (recordsBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
records_ = java.util.Collections.unmodifiableList(records_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.records_ = records_;
} else {
result.records_ = recordsBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.SSTableIndex) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.SSTableIndex)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.SSTableIndex other) {
if (other == org.cddb.lsmt.internal.TableSerializer.SSTableIndex.getDefaultInstance()) return this;
if (recordsBuilder_ == null) {
if (!other.records_.isEmpty()) {
if (records_.isEmpty()) {
records_ = other.records_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureRecordsIsMutable();
records_.addAll(other.records_);
}
onChanged();
}
} else {
if (!other.records_.isEmpty()) {
if (recordsBuilder_.isEmpty()) {
recordsBuilder_.dispose();
recordsBuilder_ = null;
records_ = other.records_;
bitField0_ = (bitField0_ & ~0x00000001);
recordsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getRecordsFieldBuilder() : null;
} else {
recordsBuilder_.addAllMessages(other.records_);
}
}
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.SSTableIndex parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.SSTableIndex) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer> records_ =
java.util.Collections.emptyList();
private void ensureRecordsIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
records_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Pointer>(records_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Pointer, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder, org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder> recordsBuilder_;
/**
* <code>repeated .Pointer records = 3;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer> getRecordsList() {
if (recordsBuilder_ == null) {
return java.util.Collections.unmodifiableList(records_);
} else {
return recordsBuilder_.getMessageList();
}
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public int getRecordsCount() {
if (recordsBuilder_ == null) {
return records_.size();
} else {
return recordsBuilder_.getCount();
}
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Pointer getRecords(int index) {
if (recordsBuilder_ == null) {
return records_.get(index);
} else {
return recordsBuilder_.getMessage(index);
}
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder setRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Pointer value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.set(index, value);
onChanged();
} else {
recordsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder setRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.set(index, builderForValue.build());
onChanged();
} else {
recordsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder addRecords(org.cddb.lsmt.internal.TableSerializer.Pointer value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.add(value);
onChanged();
} else {
recordsBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder addRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Pointer value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.add(index, value);
onChanged();
} else {
recordsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder addRecords(
org.cddb.lsmt.internal.TableSerializer.Pointer.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.add(builderForValue.build());
onChanged();
} else {
recordsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder addRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.add(index, builderForValue.build());
onChanged();
} else {
recordsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder addAllRecords(
java.lang.Iterable<? extends org.cddb.lsmt.internal.TableSerializer.Pointer> values) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, records_);
onChanged();
} else {
recordsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder clearRecords() {
if (recordsBuilder_ == null) {
records_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
recordsBuilder_.clear();
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public Builder removeRecords(int index) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.remove(index);
onChanged();
} else {
recordsBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Pointer.Builder getRecordsBuilder(
int index) {
return getRecordsFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder getRecordsOrBuilder(
int index) {
if (recordsBuilder_ == null) {
return records_.get(index); } else {
return recordsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder>
getRecordsOrBuilderList() {
if (recordsBuilder_ != null) {
return recordsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(records_);
}
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Pointer.Builder addRecordsBuilder() {
return getRecordsFieldBuilder().addBuilder(
org.cddb.lsmt.internal.TableSerializer.Pointer.getDefaultInstance());
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Pointer.Builder addRecordsBuilder(
int index) {
return getRecordsFieldBuilder().addBuilder(
index, org.cddb.lsmt.internal.TableSerializer.Pointer.getDefaultInstance());
}
/**
* <code>repeated .Pointer records = 3;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Pointer.Builder>
getRecordsBuilderList() {
return getRecordsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Pointer, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder, org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder>
getRecordsFieldBuilder() {
if (recordsBuilder_ == null) {
recordsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Pointer, org.cddb.lsmt.internal.TableSerializer.Pointer.Builder, org.cddb.lsmt.internal.TableSerializer.PointerOrBuilder>(
records_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
records_ = null;
}
return recordsBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:SSTableIndex)
}
// @@protoc_insertion_point(class_scope:SSTableIndex)
private static final org.cddb.lsmt.internal.TableSerializer.SSTableIndex DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.SSTableIndex();
}
public static org.cddb.lsmt.internal.TableSerializer.SSTableIndex getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SSTableIndex>
PARSER = new com.google.protobuf.AbstractParser<SSTableIndex>() {
public SSTableIndex parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new SSTableIndex(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<SSTableIndex> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SSTableIndex> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface RecordOrBuilder extends
// @@protoc_insertion_point(interface_extends:Record)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string key = 1;</code>
*/
java.lang.String getKey();
/**
* <code>string key = 1;</code>
*/
com.google.protobuf.ByteString
getKeyBytes();
/**
* <code>string value = 2;</code>
*/
java.lang.String getValue();
/**
* <code>string value = 2;</code>
*/
com.google.protobuf.ByteString
getValueBytes();
/**
* <code>string status = 3;</code>
*/
java.lang.String getStatus();
/**
* <code>string status = 3;</code>
*/
com.google.protobuf.ByteString
getStatusBytes();
/**
* <code>int64 timestamp = 4;</code>
*/
long getTimestamp();
}
/**
* Protobuf type {@code Record}
*/
public static final class Record extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:Record)
RecordOrBuilder {
// Use Record.newBuilder() to construct.
private Record(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Record() {
key_ = "";
value_ = "";
status_ = "";
timestamp_ = 0L;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Record(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
key_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
value_ = s;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
status_ = s;
break;
}
case 32: {
timestamp_ = input.readInt64();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Record_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Record_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Record.class, org.cddb.lsmt.internal.TableSerializer.Record.Builder.class);
}
public static final int KEY_FIELD_NUMBER = 1;
private volatile java.lang.Object key_;
/**
* <code>string key = 1;</code>
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
}
}
/**
* <code>string key = 1;</code>
*/
public com.google.protobuf.ByteString
getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VALUE_FIELD_NUMBER = 2;
private volatile java.lang.Object value_;
/**
* <code>string value = 2;</code>
*/
public java.lang.String getValue() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
value_ = s;
return s;
}
}
/**
* <code>string value = 2;</code>
*/
public com.google.protobuf.ByteString
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATUS_FIELD_NUMBER = 3;
private volatile java.lang.Object status_;
/**
* <code>string status = 3;</code>
*/
public java.lang.String getStatus() {
java.lang.Object ref = status_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
status_ = s;
return s;
}
}
/**
* <code>string status = 3;</code>
*/
public com.google.protobuf.ByteString
getStatusBytes() {
java.lang.Object ref = status_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
status_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TIMESTAMP_FIELD_NUMBER = 4;
private long timestamp_;
/**
* <code>int64 timestamp = 4;</code>
*/
public long getTimestamp() {
return timestamp_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getKeyBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, key_);
}
if (!getValueBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, value_);
}
if (!getStatusBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, status_);
}
if (timestamp_ != 0L) {
output.writeInt64(4, timestamp_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getKeyBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, key_);
}
if (!getValueBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, value_);
}
if (!getStatusBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, status_);
}
if (timestamp_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(4, timestamp_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.Record)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.Record other = (org.cddb.lsmt.internal.TableSerializer.Record) obj;
boolean result = true;
result = result && getKey()
.equals(other.getKey());
result = result && getValue()
.equals(other.getValue());
result = result && getStatus()
.equals(other.getStatus());
result = result && (getTimestamp()
== other.getTimestamp());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
hash = (37 * hash) + VALUE_FIELD_NUMBER;
hash = (53 * hash) + getValue().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + getStatus().hashCode();
hash = (37 * hash) + TIMESTAMP_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getTimestamp());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Record parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.Record prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Record}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Record)
org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Record_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Record_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Record.class, org.cddb.lsmt.internal.TableSerializer.Record.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.Record.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
key_ = "";
value_ = "";
status_ = "";
timestamp_ = 0L;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Record_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.Record getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.Record.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.Record build() {
org.cddb.lsmt.internal.TableSerializer.Record result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.Record buildPartial() {
org.cddb.lsmt.internal.TableSerializer.Record result = new org.cddb.lsmt.internal.TableSerializer.Record(this);
result.key_ = key_;
result.value_ = value_;
result.status_ = status_;
result.timestamp_ = timestamp_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.Record) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.Record)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.Record other) {
if (other == org.cddb.lsmt.internal.TableSerializer.Record.getDefaultInstance()) return this;
if (!other.getKey().isEmpty()) {
key_ = other.key_;
onChanged();
}
if (!other.getValue().isEmpty()) {
value_ = other.value_;
onChanged();
}
if (!other.getStatus().isEmpty()) {
status_ = other.status_;
onChanged();
}
if (other.getTimestamp() != 0L) {
setTimestamp(other.getTimestamp());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.Record parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.Record) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object key_ = "";
/**
* <code>string key = 1;</code>
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string key = 1;</code>
*/
public com.google.protobuf.ByteString
getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string key = 1;</code>
*/
public Builder setKey(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
onChanged();
return this;
}
/**
* <code>string key = 1;</code>
*/
public Builder clearKey() {
key_ = getDefaultInstance().getKey();
onChanged();
return this;
}
/**
* <code>string key = 1;</code>
*/
public Builder setKeyBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
key_ = value;
onChanged();
return this;
}
private java.lang.Object value_ = "";
/**
* <code>string value = 2;</code>
*/
public java.lang.String getValue() {
java.lang.Object ref = value_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
value_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string value = 2;</code>
*/
public com.google.protobuf.ByteString
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string value = 2;</code>
*/
public Builder setValue(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
value_ = value;
onChanged();
return this;
}
/**
* <code>string value = 2;</code>
*/
public Builder clearValue() {
value_ = getDefaultInstance().getValue();
onChanged();
return this;
}
/**
* <code>string value = 2;</code>
*/
public Builder setValueBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
value_ = value;
onChanged();
return this;
}
private java.lang.Object status_ = "";
/**
* <code>string status = 3;</code>
*/
public java.lang.String getStatus() {
java.lang.Object ref = status_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
status_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string status = 3;</code>
*/
public com.google.protobuf.ByteString
getStatusBytes() {
java.lang.Object ref = status_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
status_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string status = 3;</code>
*/
public Builder setStatus(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
status_ = value;
onChanged();
return this;
}
/**
* <code>string status = 3;</code>
*/
public Builder clearStatus() {
status_ = getDefaultInstance().getStatus();
onChanged();
return this;
}
/**
* <code>string status = 3;</code>
*/
public Builder setStatusBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
status_ = value;
onChanged();
return this;
}
private long timestamp_ ;
/**
* <code>int64 timestamp = 4;</code>
*/
public long getTimestamp() {
return timestamp_;
}
/**
* <code>int64 timestamp = 4;</code>
*/
public Builder setTimestamp(long value) {
timestamp_ = value;
onChanged();
return this;
}
/**
* <code>int64 timestamp = 4;</code>
*/
public Builder clearTimestamp() {
timestamp_ = 0L;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:Record)
}
// @@protoc_insertion_point(class_scope:Record)
private static final org.cddb.lsmt.internal.TableSerializer.Record DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.Record();
}
public static org.cddb.lsmt.internal.TableSerializer.Record getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Record>
PARSER = new com.google.protobuf.AbstractParser<Record>() {
public Record parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Record(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Record> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Record> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.Record getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface SSTableOrBuilder extends
// @@protoc_insertion_point(interface_extends:SSTable)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.SSTableIndex index = 1;</code>
*/
boolean hasIndex();
/**
* <code>.SSTableIndex index = 1;</code>
*/
org.cddb.lsmt.internal.TableSerializer.SSTableIndex getIndex();
/**
* <code>.SSTableIndex index = 1;</code>
*/
org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder getIndexOrBuilder();
/**
* <code>repeated .Record records = 2;</code>
*/
java.util.List<org.cddb.lsmt.internal.TableSerializer.Record>
getRecordsList();
/**
* <code>repeated .Record records = 2;</code>
*/
org.cddb.lsmt.internal.TableSerializer.Record getRecords(int index);
/**
* <code>repeated .Record records = 2;</code>
*/
int getRecordsCount();
/**
* <code>repeated .Record records = 2;</code>
*/
java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder>
getRecordsOrBuilderList();
/**
* <code>repeated .Record records = 2;</code>
*/
org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder getRecordsOrBuilder(
int index);
}
/**
* Protobuf type {@code SSTable}
*/
public static final class SSTable extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:SSTable)
SSTableOrBuilder {
// Use SSTable.newBuilder() to construct.
private SSTable(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SSTable() {
records_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private SSTable(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder subBuilder = null;
if (index_ != null) {
subBuilder = index_.toBuilder();
}
index_ = input.readMessage(org.cddb.lsmt.internal.TableSerializer.SSTableIndex.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(index_);
index_ = subBuilder.buildPartial();
}
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
records_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Record>();
mutable_bitField0_ |= 0x00000002;
}
records_.add(
input.readMessage(org.cddb.lsmt.internal.TableSerializer.Record.parser(), extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
records_ = java.util.Collections.unmodifiableList(records_);
}
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTable_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTable_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.SSTable.class, org.cddb.lsmt.internal.TableSerializer.SSTable.Builder.class);
}
private int bitField0_;
public static final int INDEX_FIELD_NUMBER = 1;
private org.cddb.lsmt.internal.TableSerializer.SSTableIndex index_;
/**
* <code>.SSTableIndex index = 1;</code>
*/
public boolean hasIndex() {
return index_ != null;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex getIndex() {
return index_ == null ? org.cddb.lsmt.internal.TableSerializer.SSTableIndex.getDefaultInstance() : index_;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder getIndexOrBuilder() {
return getIndex();
}
public static final int RECORDS_FIELD_NUMBER = 2;
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Record> records_;
/**
* <code>repeated .Record records = 2;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Record> getRecordsList() {
return records_;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder>
getRecordsOrBuilderList() {
return records_;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public int getRecordsCount() {
return records_.size();
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Record getRecords(int index) {
return records_.get(index);
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder getRecordsOrBuilder(
int index) {
return records_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (index_ != null) {
output.writeMessage(1, getIndex());
}
for (int i = 0; i < records_.size(); i++) {
output.writeMessage(2, records_.get(i));
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (index_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getIndex());
}
for (int i = 0; i < records_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, records_.get(i));
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.SSTable)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.SSTable other = (org.cddb.lsmt.internal.TableSerializer.SSTable) obj;
boolean result = true;
result = result && (hasIndex() == other.hasIndex());
if (hasIndex()) {
result = result && getIndex()
.equals(other.getIndex());
}
result = result && getRecordsList()
.equals(other.getRecordsList());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasIndex()) {
hash = (37 * hash) + INDEX_FIELD_NUMBER;
hash = (53 * hash) + getIndex().hashCode();
}
if (getRecordsCount() > 0) {
hash = (37 * hash) + RECORDS_FIELD_NUMBER;
hash = (53 * hash) + getRecordsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.SSTable prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code SSTable}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:SSTable)
org.cddb.lsmt.internal.TableSerializer.SSTableOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTable_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTable_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.SSTable.class, org.cddb.lsmt.internal.TableSerializer.SSTable.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.SSTable.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getRecordsFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (indexBuilder_ == null) {
index_ = null;
} else {
index_ = null;
indexBuilder_ = null;
}
if (recordsBuilder_ == null) {
records_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
} else {
recordsBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_SSTable_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.SSTable getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.SSTable.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.SSTable build() {
org.cddb.lsmt.internal.TableSerializer.SSTable result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.SSTable buildPartial() {
org.cddb.lsmt.internal.TableSerializer.SSTable result = new org.cddb.lsmt.internal.TableSerializer.SSTable(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (indexBuilder_ == null) {
result.index_ = index_;
} else {
result.index_ = indexBuilder_.build();
}
if (recordsBuilder_ == null) {
if (((bitField0_ & 0x00000002) == 0x00000002)) {
records_ = java.util.Collections.unmodifiableList(records_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.records_ = records_;
} else {
result.records_ = recordsBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.SSTable) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.SSTable)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.SSTable other) {
if (other == org.cddb.lsmt.internal.TableSerializer.SSTable.getDefaultInstance()) return this;
if (other.hasIndex()) {
mergeIndex(other.getIndex());
}
if (recordsBuilder_ == null) {
if (!other.records_.isEmpty()) {
if (records_.isEmpty()) {
records_ = other.records_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureRecordsIsMutable();
records_.addAll(other.records_);
}
onChanged();
}
} else {
if (!other.records_.isEmpty()) {
if (recordsBuilder_.isEmpty()) {
recordsBuilder_.dispose();
recordsBuilder_ = null;
records_ = other.records_;
bitField0_ = (bitField0_ & ~0x00000002);
recordsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getRecordsFieldBuilder() : null;
} else {
recordsBuilder_.addAllMessages(other.records_);
}
}
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.SSTable parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.SSTable) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private org.cddb.lsmt.internal.TableSerializer.SSTableIndex index_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.SSTableIndex, org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder, org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder> indexBuilder_;
/**
* <code>.SSTableIndex index = 1;</code>
*/
public boolean hasIndex() {
return indexBuilder_ != null || index_ != null;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex getIndex() {
if (indexBuilder_ == null) {
return index_ == null ? org.cddb.lsmt.internal.TableSerializer.SSTableIndex.getDefaultInstance() : index_;
} else {
return indexBuilder_.getMessage();
}
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public Builder setIndex(org.cddb.lsmt.internal.TableSerializer.SSTableIndex value) {
if (indexBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
index_ = value;
onChanged();
} else {
indexBuilder_.setMessage(value);
}
return this;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public Builder setIndex(
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder builderForValue) {
if (indexBuilder_ == null) {
index_ = builderForValue.build();
onChanged();
} else {
indexBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public Builder mergeIndex(org.cddb.lsmt.internal.TableSerializer.SSTableIndex value) {
if (indexBuilder_ == null) {
if (index_ != null) {
index_ =
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.newBuilder(index_).mergeFrom(value).buildPartial();
} else {
index_ = value;
}
onChanged();
} else {
indexBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public Builder clearIndex() {
if (indexBuilder_ == null) {
index_ = null;
onChanged();
} else {
index_ = null;
indexBuilder_ = null;
}
return this;
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder getIndexBuilder() {
onChanged();
return getIndexFieldBuilder().getBuilder();
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder getIndexOrBuilder() {
if (indexBuilder_ != null) {
return indexBuilder_.getMessageOrBuilder();
} else {
return index_ == null ?
org.cddb.lsmt.internal.TableSerializer.SSTableIndex.getDefaultInstance() : index_;
}
}
/**
* <code>.SSTableIndex index = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.SSTableIndex, org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder, org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder>
getIndexFieldBuilder() {
if (indexBuilder_ == null) {
indexBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.SSTableIndex, org.cddb.lsmt.internal.TableSerializer.SSTableIndex.Builder, org.cddb.lsmt.internal.TableSerializer.SSTableIndexOrBuilder>(
getIndex(),
getParentForChildren(),
isClean());
index_ = null;
}
return indexBuilder_;
}
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Record> records_ =
java.util.Collections.emptyList();
private void ensureRecordsIsMutable() {
if (!((bitField0_ & 0x00000002) == 0x00000002)) {
records_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Record>(records_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Record, org.cddb.lsmt.internal.TableSerializer.Record.Builder, org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder> recordsBuilder_;
/**
* <code>repeated .Record records = 2;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Record> getRecordsList() {
if (recordsBuilder_ == null) {
return java.util.Collections.unmodifiableList(records_);
} else {
return recordsBuilder_.getMessageList();
}
}
/**
* <code>repeated .Record records = 2;</code>
*/
public int getRecordsCount() {
if (recordsBuilder_ == null) {
return records_.size();
} else {
return recordsBuilder_.getCount();
}
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Record getRecords(int index) {
if (recordsBuilder_ == null) {
return records_.get(index);
} else {
return recordsBuilder_.getMessage(index);
}
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder setRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Record value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.set(index, value);
onChanged();
} else {
recordsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder setRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Record.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.set(index, builderForValue.build());
onChanged();
} else {
recordsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder addRecords(org.cddb.lsmt.internal.TableSerializer.Record value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.add(value);
onChanged();
} else {
recordsBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder addRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Record value) {
if (recordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecordsIsMutable();
records_.add(index, value);
onChanged();
} else {
recordsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder addRecords(
org.cddb.lsmt.internal.TableSerializer.Record.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.add(builderForValue.build());
onChanged();
} else {
recordsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder addRecords(
int index, org.cddb.lsmt.internal.TableSerializer.Record.Builder builderForValue) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.add(index, builderForValue.build());
onChanged();
} else {
recordsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder addAllRecords(
java.lang.Iterable<? extends org.cddb.lsmt.internal.TableSerializer.Record> values) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, records_);
onChanged();
} else {
recordsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder clearRecords() {
if (recordsBuilder_ == null) {
records_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
recordsBuilder_.clear();
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public Builder removeRecords(int index) {
if (recordsBuilder_ == null) {
ensureRecordsIsMutable();
records_.remove(index);
onChanged();
} else {
recordsBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Record.Builder getRecordsBuilder(
int index) {
return getRecordsFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder getRecordsOrBuilder(
int index) {
if (recordsBuilder_ == null) {
return records_.get(index); } else {
return recordsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .Record records = 2;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder>
getRecordsOrBuilderList() {
if (recordsBuilder_ != null) {
return recordsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(records_);
}
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Record.Builder addRecordsBuilder() {
return getRecordsFieldBuilder().addBuilder(
org.cddb.lsmt.internal.TableSerializer.Record.getDefaultInstance());
}
/**
* <code>repeated .Record records = 2;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Record.Builder addRecordsBuilder(
int index) {
return getRecordsFieldBuilder().addBuilder(
index, org.cddb.lsmt.internal.TableSerializer.Record.getDefaultInstance());
}
/**
* <code>repeated .Record records = 2;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Record.Builder>
getRecordsBuilderList() {
return getRecordsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Record, org.cddb.lsmt.internal.TableSerializer.Record.Builder, org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder>
getRecordsFieldBuilder() {
if (recordsBuilder_ == null) {
recordsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Record, org.cddb.lsmt.internal.TableSerializer.Record.Builder, org.cddb.lsmt.internal.TableSerializer.RecordOrBuilder>(
records_,
((bitField0_ & 0x00000002) == 0x00000002),
getParentForChildren(),
isClean());
records_ = null;
}
return recordsBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:SSTable)
}
// @@protoc_insertion_point(class_scope:SSTable)
private static final org.cddb.lsmt.internal.TableSerializer.SSTable DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.SSTable();
}
public static org.cddb.lsmt.internal.TableSerializer.SSTable getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SSTable>
PARSER = new com.google.protobuf.AbstractParser<SSTable>() {
public SSTable parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new SSTable(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<SSTable> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SSTable> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.SSTable getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface MetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:Metadata)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string from = 1;</code>
*/
java.lang.String getFrom();
/**
* <code>string from = 1;</code>
*/
com.google.protobuf.ByteString
getFromBytes();
/**
* <code>string to = 2;</code>
*/
java.lang.String getTo();
/**
* <code>string to = 2;</code>
*/
com.google.protobuf.ByteString
getToBytes();
/**
* <code>string blockId = 3;</code>
*/
java.lang.String getBlockId();
/**
* <code>string blockId = 3;</code>
*/
com.google.protobuf.ByteString
getBlockIdBytes();
/**
* <code>int64 timestamp = 4;</code>
*/
long getTimestamp();
}
/**
* Protobuf type {@code Metadata}
*/
public static final class Metadata extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:Metadata)
MetadataOrBuilder {
// Use Metadata.newBuilder() to construct.
private Metadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Metadata() {
from_ = "";
to_ = "";
blockId_ = "";
timestamp_ = 0L;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Metadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
from_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
to_ = s;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
blockId_ = s;
break;
}
case 32: {
timestamp_ = input.readInt64();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Metadata_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Metadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Metadata.class, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder.class);
}
public static final int FROM_FIELD_NUMBER = 1;
private volatile java.lang.Object from_;
/**
* <code>string from = 1;</code>
*/
public java.lang.String getFrom() {
java.lang.Object ref = from_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
from_ = s;
return s;
}
}
/**
* <code>string from = 1;</code>
*/
public com.google.protobuf.ByteString
getFromBytes() {
java.lang.Object ref = from_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
from_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TO_FIELD_NUMBER = 2;
private volatile java.lang.Object to_;
/**
* <code>string to = 2;</code>
*/
public java.lang.String getTo() {
java.lang.Object ref = to_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
to_ = s;
return s;
}
}
/**
* <code>string to = 2;</code>
*/
public com.google.protobuf.ByteString
getToBytes() {
java.lang.Object ref = to_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
to_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int BLOCKID_FIELD_NUMBER = 3;
private volatile java.lang.Object blockId_;
/**
* <code>string blockId = 3;</code>
*/
public java.lang.String getBlockId() {
java.lang.Object ref = blockId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
blockId_ = s;
return s;
}
}
/**
* <code>string blockId = 3;</code>
*/
public com.google.protobuf.ByteString
getBlockIdBytes() {
java.lang.Object ref = blockId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
blockId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TIMESTAMP_FIELD_NUMBER = 4;
private long timestamp_;
/**
* <code>int64 timestamp = 4;</code>
*/
public long getTimestamp() {
return timestamp_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getFromBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, from_);
}
if (!getToBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, to_);
}
if (!getBlockIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, blockId_);
}
if (timestamp_ != 0L) {
output.writeInt64(4, timestamp_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getFromBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, from_);
}
if (!getToBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, to_);
}
if (!getBlockIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, blockId_);
}
if (timestamp_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(4, timestamp_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.Metadata)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.Metadata other = (org.cddb.lsmt.internal.TableSerializer.Metadata) obj;
boolean result = true;
result = result && getFrom()
.equals(other.getFrom());
result = result && getTo()
.equals(other.getTo());
result = result && getBlockId()
.equals(other.getBlockId());
result = result && (getTimestamp()
== other.getTimestamp());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + FROM_FIELD_NUMBER;
hash = (53 * hash) + getFrom().hashCode();
hash = (37 * hash) + TO_FIELD_NUMBER;
hash = (53 * hash) + getTo().hashCode();
hash = (37 * hash) + BLOCKID_FIELD_NUMBER;
hash = (53 * hash) + getBlockId().hashCode();
hash = (37 * hash) + TIMESTAMP_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getTimestamp());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.Metadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Metadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Metadata)
org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Metadata_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Metadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.Metadata.class, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.Metadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
from_ = "";
to_ = "";
blockId_ = "";
timestamp_ = 0L;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_Metadata_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.Metadata getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.Metadata.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.Metadata build() {
org.cddb.lsmt.internal.TableSerializer.Metadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.Metadata buildPartial() {
org.cddb.lsmt.internal.TableSerializer.Metadata result = new org.cddb.lsmt.internal.TableSerializer.Metadata(this);
result.from_ = from_;
result.to_ = to_;
result.blockId_ = blockId_;
result.timestamp_ = timestamp_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.Metadata) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.Metadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.Metadata other) {
if (other == org.cddb.lsmt.internal.TableSerializer.Metadata.getDefaultInstance()) return this;
if (!other.getFrom().isEmpty()) {
from_ = other.from_;
onChanged();
}
if (!other.getTo().isEmpty()) {
to_ = other.to_;
onChanged();
}
if (!other.getBlockId().isEmpty()) {
blockId_ = other.blockId_;
onChanged();
}
if (other.getTimestamp() != 0L) {
setTimestamp(other.getTimestamp());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.Metadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.Metadata) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object from_ = "";
/**
* <code>string from = 1;</code>
*/
public java.lang.String getFrom() {
java.lang.Object ref = from_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
from_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string from = 1;</code>
*/
public com.google.protobuf.ByteString
getFromBytes() {
java.lang.Object ref = from_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
from_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string from = 1;</code>
*/
public Builder setFrom(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
from_ = value;
onChanged();
return this;
}
/**
* <code>string from = 1;</code>
*/
public Builder clearFrom() {
from_ = getDefaultInstance().getFrom();
onChanged();
return this;
}
/**
* <code>string from = 1;</code>
*/
public Builder setFromBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
from_ = value;
onChanged();
return this;
}
private java.lang.Object to_ = "";
/**
* <code>string to = 2;</code>
*/
public java.lang.String getTo() {
java.lang.Object ref = to_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
to_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string to = 2;</code>
*/
public com.google.protobuf.ByteString
getToBytes() {
java.lang.Object ref = to_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
to_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string to = 2;</code>
*/
public Builder setTo(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
to_ = value;
onChanged();
return this;
}
/**
* <code>string to = 2;</code>
*/
public Builder clearTo() {
to_ = getDefaultInstance().getTo();
onChanged();
return this;
}
/**
* <code>string to = 2;</code>
*/
public Builder setToBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
to_ = value;
onChanged();
return this;
}
private java.lang.Object blockId_ = "";
/**
* <code>string blockId = 3;</code>
*/
public java.lang.String getBlockId() {
java.lang.Object ref = blockId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
blockId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string blockId = 3;</code>
*/
public com.google.protobuf.ByteString
getBlockIdBytes() {
java.lang.Object ref = blockId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
blockId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string blockId = 3;</code>
*/
public Builder setBlockId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
blockId_ = value;
onChanged();
return this;
}
/**
* <code>string blockId = 3;</code>
*/
public Builder clearBlockId() {
blockId_ = getDefaultInstance().getBlockId();
onChanged();
return this;
}
/**
* <code>string blockId = 3;</code>
*/
public Builder setBlockIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
blockId_ = value;
onChanged();
return this;
}
private long timestamp_ ;
/**
* <code>int64 timestamp = 4;</code>
*/
public long getTimestamp() {
return timestamp_;
}
/**
* <code>int64 timestamp = 4;</code>
*/
public Builder setTimestamp(long value) {
timestamp_ = value;
onChanged();
return this;
}
/**
* <code>int64 timestamp = 4;</code>
*/
public Builder clearTimestamp() {
timestamp_ = 0L;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:Metadata)
}
// @@protoc_insertion_point(class_scope:Metadata)
private static final org.cddb.lsmt.internal.TableSerializer.Metadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.Metadata();
}
public static org.cddb.lsmt.internal.TableSerializer.Metadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Metadata>
PARSER = new com.google.protobuf.AbstractParser<Metadata>() {
public Metadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Metadata(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Metadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Metadata> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.Metadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface DataIndexOrBuilder extends
// @@protoc_insertion_point(interface_extends:DataIndex)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .Metadata indices = 1;</code>
*/
java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata>
getIndicesList();
/**
* <code>repeated .Metadata indices = 1;</code>
*/
org.cddb.lsmt.internal.TableSerializer.Metadata getIndices(int index);
/**
* <code>repeated .Metadata indices = 1;</code>
*/
int getIndicesCount();
/**
* <code>repeated .Metadata indices = 1;</code>
*/
java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder>
getIndicesOrBuilderList();
/**
* <code>repeated .Metadata indices = 1;</code>
*/
org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder getIndicesOrBuilder(
int index);
}
/**
* Protobuf type {@code DataIndex}
*/
public static final class DataIndex extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:DataIndex)
DataIndexOrBuilder {
// Use DataIndex.newBuilder() to construct.
private DataIndex(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DataIndex() {
indices_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private DataIndex(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
indices_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Metadata>();
mutable_bitField0_ |= 0x00000001;
}
indices_.add(
input.readMessage(org.cddb.lsmt.internal.TableSerializer.Metadata.parser(), extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
indices_ = java.util.Collections.unmodifiableList(indices_);
}
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_DataIndex_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_DataIndex_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.DataIndex.class, org.cddb.lsmt.internal.TableSerializer.DataIndex.Builder.class);
}
public static final int INDICES_FIELD_NUMBER = 1;
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata> indices_;
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata> getIndicesList() {
return indices_;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder>
getIndicesOrBuilderList() {
return indices_;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public int getIndicesCount() {
return indices_.size();
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Metadata getIndices(int index) {
return indices_.get(index);
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder getIndicesOrBuilder(
int index) {
return indices_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < indices_.size(); i++) {
output.writeMessage(1, indices_.get(i));
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < indices_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, indices_.get(i));
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.cddb.lsmt.internal.TableSerializer.DataIndex)) {
return super.equals(obj);
}
org.cddb.lsmt.internal.TableSerializer.DataIndex other = (org.cddb.lsmt.internal.TableSerializer.DataIndex) obj;
boolean result = true;
result = result && getIndicesList()
.equals(other.getIndicesList());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getIndicesCount() > 0) {
hash = (37 * hash) + INDICES_FIELD_NUMBER;
hash = (53 * hash) + getIndicesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.cddb.lsmt.internal.TableSerializer.DataIndex prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code DataIndex}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:DataIndex)
org.cddb.lsmt.internal.TableSerializer.DataIndexOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_DataIndex_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_DataIndex_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.cddb.lsmt.internal.TableSerializer.DataIndex.class, org.cddb.lsmt.internal.TableSerializer.DataIndex.Builder.class);
}
// Construct using org.cddb.lsmt.internal.TableSerializer.DataIndex.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getIndicesFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (indicesBuilder_ == null) {
indices_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
indicesBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.cddb.lsmt.internal.TableSerializer.internal_static_DataIndex_descriptor;
}
public org.cddb.lsmt.internal.TableSerializer.DataIndex getDefaultInstanceForType() {
return org.cddb.lsmt.internal.TableSerializer.DataIndex.getDefaultInstance();
}
public org.cddb.lsmt.internal.TableSerializer.DataIndex build() {
org.cddb.lsmt.internal.TableSerializer.DataIndex result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.cddb.lsmt.internal.TableSerializer.DataIndex buildPartial() {
org.cddb.lsmt.internal.TableSerializer.DataIndex result = new org.cddb.lsmt.internal.TableSerializer.DataIndex(this);
int from_bitField0_ = bitField0_;
if (indicesBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
indices_ = java.util.Collections.unmodifiableList(indices_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.indices_ = indices_;
} else {
result.indices_ = indicesBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.cddb.lsmt.internal.TableSerializer.DataIndex) {
return mergeFrom((org.cddb.lsmt.internal.TableSerializer.DataIndex)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.cddb.lsmt.internal.TableSerializer.DataIndex other) {
if (other == org.cddb.lsmt.internal.TableSerializer.DataIndex.getDefaultInstance()) return this;
if (indicesBuilder_ == null) {
if (!other.indices_.isEmpty()) {
if (indices_.isEmpty()) {
indices_ = other.indices_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureIndicesIsMutable();
indices_.addAll(other.indices_);
}
onChanged();
}
} else {
if (!other.indices_.isEmpty()) {
if (indicesBuilder_.isEmpty()) {
indicesBuilder_.dispose();
indicesBuilder_ = null;
indices_ = other.indices_;
bitField0_ = (bitField0_ & ~0x00000001);
indicesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getIndicesFieldBuilder() : null;
} else {
indicesBuilder_.addAllMessages(other.indices_);
}
}
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.cddb.lsmt.internal.TableSerializer.DataIndex parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.cddb.lsmt.internal.TableSerializer.DataIndex) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata> indices_ =
java.util.Collections.emptyList();
private void ensureIndicesIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
indices_ = new java.util.ArrayList<org.cddb.lsmt.internal.TableSerializer.Metadata>(indices_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Metadata, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder, org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder> indicesBuilder_;
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata> getIndicesList() {
if (indicesBuilder_ == null) {
return java.util.Collections.unmodifiableList(indices_);
} else {
return indicesBuilder_.getMessageList();
}
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public int getIndicesCount() {
if (indicesBuilder_ == null) {
return indices_.size();
} else {
return indicesBuilder_.getCount();
}
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Metadata getIndices(int index) {
if (indicesBuilder_ == null) {
return indices_.get(index);
} else {
return indicesBuilder_.getMessage(index);
}
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder setIndices(
int index, org.cddb.lsmt.internal.TableSerializer.Metadata value) {
if (indicesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureIndicesIsMutable();
indices_.set(index, value);
onChanged();
} else {
indicesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder setIndices(
int index, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder builderForValue) {
if (indicesBuilder_ == null) {
ensureIndicesIsMutable();
indices_.set(index, builderForValue.build());
onChanged();
} else {
indicesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder addIndices(org.cddb.lsmt.internal.TableSerializer.Metadata value) {
if (indicesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureIndicesIsMutable();
indices_.add(value);
onChanged();
} else {
indicesBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder addIndices(
int index, org.cddb.lsmt.internal.TableSerializer.Metadata value) {
if (indicesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureIndicesIsMutable();
indices_.add(index, value);
onChanged();
} else {
indicesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder addIndices(
org.cddb.lsmt.internal.TableSerializer.Metadata.Builder builderForValue) {
if (indicesBuilder_ == null) {
ensureIndicesIsMutable();
indices_.add(builderForValue.build());
onChanged();
} else {
indicesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder addIndices(
int index, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder builderForValue) {
if (indicesBuilder_ == null) {
ensureIndicesIsMutable();
indices_.add(index, builderForValue.build());
onChanged();
} else {
indicesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder addAllIndices(
java.lang.Iterable<? extends org.cddb.lsmt.internal.TableSerializer.Metadata> values) {
if (indicesBuilder_ == null) {
ensureIndicesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, indices_);
onChanged();
} else {
indicesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder clearIndices() {
if (indicesBuilder_ == null) {
indices_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
indicesBuilder_.clear();
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public Builder removeIndices(int index) {
if (indicesBuilder_ == null) {
ensureIndicesIsMutable();
indices_.remove(index);
onChanged();
} else {
indicesBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Metadata.Builder getIndicesBuilder(
int index) {
return getIndicesFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder getIndicesOrBuilder(
int index) {
if (indicesBuilder_ == null) {
return indices_.get(index); } else {
return indicesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public java.util.List<? extends org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder>
getIndicesOrBuilderList() {
if (indicesBuilder_ != null) {
return indicesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(indices_);
}
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Metadata.Builder addIndicesBuilder() {
return getIndicesFieldBuilder().addBuilder(
org.cddb.lsmt.internal.TableSerializer.Metadata.getDefaultInstance());
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public org.cddb.lsmt.internal.TableSerializer.Metadata.Builder addIndicesBuilder(
int index) {
return getIndicesFieldBuilder().addBuilder(
index, org.cddb.lsmt.internal.TableSerializer.Metadata.getDefaultInstance());
}
/**
* <code>repeated .Metadata indices = 1;</code>
*/
public java.util.List<org.cddb.lsmt.internal.TableSerializer.Metadata.Builder>
getIndicesBuilderList() {
return getIndicesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Metadata, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder, org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder>
getIndicesFieldBuilder() {
if (indicesBuilder_ == null) {
indicesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
org.cddb.lsmt.internal.TableSerializer.Metadata, org.cddb.lsmt.internal.TableSerializer.Metadata.Builder, org.cddb.lsmt.internal.TableSerializer.MetadataOrBuilder>(
indices_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
indices_ = null;
}
return indicesBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:DataIndex)
}
// @@protoc_insertion_point(class_scope:DataIndex)
private static final org.cddb.lsmt.internal.TableSerializer.DataIndex DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.cddb.lsmt.internal.TableSerializer.DataIndex();
}
public static org.cddb.lsmt.internal.TableSerializer.DataIndex getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DataIndex>
PARSER = new com.google.protobuf.AbstractParser<DataIndex>() {
public DataIndex parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DataIndex(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DataIndex> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DataIndex> getParserForType() {
return PARSER;
}
public org.cddb.lsmt.internal.TableSerializer.DataIndex getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Pointer_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_Pointer_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_SSTableIndex_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_SSTableIndex_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Record_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_Record_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_SSTable_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_SSTable_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Metadata_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_Metadata_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_DataIndex_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_DataIndex_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\013table.proto\"6\n\007Pointer\022\013\n\003key\030\001 \001(\t\022\016\n" +
"\006offset\030\002 \001(\005\022\016\n\006length\030\003 \001(\005\")\n\014SSTable" +
"Index\022\031\n\007records\030\003 \003(\0132\010.Pointer\"G\n\006Reco" +
"rd\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\022\016\n\006status" +
"\030\003 \001(\t\022\021\n\ttimestamp\030\004 \001(\003\"A\n\007SSTable\022\034\n\005" +
"index\030\001 \001(\0132\r.SSTableIndex\022\030\n\007records\030\002 " +
"\003(\0132\007.Record\"H\n\010Metadata\022\014\n\004from\030\001 \001(\t\022\n" +
"\n\002to\030\002 \001(\t\022\017\n\007blockId\030\003 \001(\t\022\021\n\ttimestamp" +
"\030\004 \001(\003\"\'\n\tDataIndex\022\032\n\007indices\030\001 \003(\0132\t.M" +
"etadataB)\n\026org.cddb.lsmt.internalB\017Table",
"Serializerb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_Pointer_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Pointer_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Pointer_descriptor,
new java.lang.String[] { "Key", "Offset", "Length", });
internal_static_SSTableIndex_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_SSTableIndex_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_SSTableIndex_descriptor,
new java.lang.String[] { "Records", });
internal_static_Record_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_Record_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Record_descriptor,
new java.lang.String[] { "Key", "Value", "Status", "Timestamp", });
internal_static_SSTable_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_SSTable_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_SSTable_descriptor,
new java.lang.String[] { "Index", "Records", });
internal_static_Metadata_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_Metadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Metadata_descriptor,
new java.lang.String[] { "From", "To", "BlockId", "Timestamp", });
internal_static_DataIndex_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_DataIndex_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_DataIndex_descriptor,
new java.lang.String[] { "Indices", });
}
// @@protoc_insertion_point(outer_class_scope)
}
|
package entities.enemies;
import entities.Entity;
import world.World;
public abstract class Enemy extends Entity{
public Enemy(int height, int width, int chunkNo, float posX, float posY) {
super(height, width, chunkNo, posX, posY);
}
@Override
public void onDestruction() {
World.world.get(getChunkNo()).getEntities().remove(this);
}
}
|
package com.zou.gulimall.product;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 整合Mybatis-Plus
* 1. 导入依赖
* 2. 配置
* 1. 配置数据源
* 1. 导入Mysql驱动依赖
* 2. 在yml中配置数据源信息
* 2. 配置MyBatis-Plus:
* 1. 使用@MapperScan
* 2. yml中 告诉MyBatis-Plus,sql映射文件位置
*/
@SpringBootApplication
@MapperScan("com.zou.gulimall.product.dao")
public class GulimallProductApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallProductApplication.class, args);
}
}
|
package ch.endte.syncmatica.mixin;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.packet.c2s.play.CustomPayloadC2SPacket;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(CustomPayloadC2SPacket.class)
public interface MixinCustomPayloadC2SPacket {
@Accessor("channel")
public Identifier getChannel();
@Accessor("data")
public PacketByteBuf getData();
}
|
package projects.sample3.nodes.timers;
import lombok.Getter;
import lombok.Setter;
import projects.sample3.nodes.messages.SmsMessage;
import projects.sample3.nodes.nodeImplementations.Antenna;
import projects.sample3.nodes.nodeImplementations.MobileNode;
import sinalgo.nodes.Node;
import sinalgo.nodes.timers.Timer;
@Getter
@Setter
public class SmsTimer extends Timer {
private String text;
private Node destination;
private boolean enabled = true;
public void disable() {
this.setEnabled(false);
}
public SmsTimer(String aText, Node aDestination) {
this.setText(aText);
this.setDestination(aDestination);
}
@Override
public void fire() {
if (this.isEnabled()) {
MobileNode mn = (MobileNode) this.getTargetNode();
// Assemble an SMS and send it to the current anteanna
SmsMessage msg = new SmsMessage(mn.getNextSeqID(), this.getDestination(), this.getTargetNode(), this.getText(), this);
Antenna a = mn.getCurrentAntenna();
if (a != null) {
this.getTargetNode().send(msg, a);
}
this.startRelative(8, this.getTargetNode()); // TODO: time?
}
}
}
|
package org.myrobotlab.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
public class Database extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Database.class);
public static String driver = "com.mysql.jdbc.Driver";
public static String connectionString = ""; // e.g.//
// "jdbc:mysql://HOST/DATABASE"
public static String jdbcUser = "user";
public static String jdbcPassword = "password";
static Connection connection = null;
public Database(String n, String id) {
super(n, id);
}
public static void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Class.forName(driver);
connection = DriverManager.getConnection(connectionString, jdbcUser, jdbcPassword);
}
public void closeConnection() throws SQLException {
connection.close();
}
public int executeUpdate(String sql) throws SQLException {
Statement statement = connection.createStatement();
// execute insert SQL statement
return statement.executeUpdate(sql);
}
public static ResultSet executeQuery(String sql) throws SQLException {
Statement statement = connection.createStatement();
// execute insert SQL statement
return statement.executeQuery(sql);
}
public boolean execute(String sql) throws SQLException {
Statement statement = connection.createStatement();
// execute insert SQL statement
return statement.execute(sql);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Database.class.getCanonicalName());
meta.addDescription("database - wrapper around jdbc access");
meta.setAvailable(true); // false if you do not want it viewable in a
// gui
// add dependency if necessary
// meta.addDependency("org.coolproject", "1.0.0");
meta.addCategory("storage");
return meta;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
LoggingFactory.init("INFO");
// connect();
// ResultSet rs = executeQuery("SELECT * FROM uptime");
// while (rs.next()) {
// log.info(rs.getString("id"));
// }
}
}
|
package io.greenscape.gconfigd.model.impl;
import io.greenscape.gconfigd.model.User;
public class UserImpl implements User {
public Long getId() {
return 1L;
}
public String getName() {
return "Default";
}
@Override
public String toString() {
return "User [id=" + getId() + ", name=" + getName() + "]";
}
}
|
package uk.gov.companieshouse.efs.web.formtemplates.service.api;
import uk.gov.companieshouse.api.InternalApiClient;
import uk.gov.companieshouse.api.model.ApiResponse;
import uk.gov.companieshouse.api.model.efs.formtemplates.FormTemplateApi;
import uk.gov.companieshouse.api.model.efs.formtemplates.FormTemplateListApi;
/**
* The {@code FormTemplateService} interface provides an abstraction that can be
* used when testing {@code FormTemplateService} static methods, without imposing
* the use of a test framework that supports mocking of static methods.
*/
public interface FormTemplateService {
InternalApiClient getApiClient();
/**
* Form template list response object.
*
* @return the list of form models for the json response
*/
ApiResponse<FormTemplateListApi> getFormTemplates();
/**
* Form template response object.
*
* @return the form template for the json response
*/
ApiResponse<FormTemplateApi> getFormTemplate(String id);
/**
* Form template list response object.
*
* @return the form template list for the json response
*/
ApiResponse<FormTemplateListApi> getFormTemplatesByCategory(String id);
}
|
public class Context implements Strategy{
private Strategy _s;
public Context(Strategy s){
_s = s;
}
public int doOperation(int a,int b){
return _s.doOperation(a,b);
}
}
|
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved
// 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 com.baidu.palo.broker.bos;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
public class BosBlockBuffer {
private String key;
private int blkId;
DataOutputBuffer outBuffer;
DataInputBuffer inBuffer = new DataInputBuffer();
public BosBlockBuffer(String key, int blkId, int size) {
this.key = key;
this.blkId = blkId;
outBuffer = new DataOutputBuffer(size);
}
public String getKey() {
return key;
}
public int getBlkId() {
return blkId;
}
public void setBlkId(int blkId) {
this.blkId = blkId;
}
void moveData() {
inBuffer.reset(outBuffer.getData(), outBuffer.getLength());
outBuffer = new DataOutputBuffer(1);
}
void clear() {
inBuffer.reset(null, 0);
}
}
|
/*
* 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.dubbo.registry.consul;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.status.RegistryStatusChecker;
import com.pszymczyk.consul.ConsulProcess;
import com.pszymczyk.consul.ConsulStarterBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
public class ConsulRegistryTest {
private ConsulProcess consul;
private ConsulRegistry consulRegistry;
private String service = "org.apache.dubbo.test.injvmServie";
private URL serviceUrl = URL.valueOf("consul://127.0.0.1:" + NetUtils.getAvailablePort() + "/" + service + "?notify=false&methods=test1,test2");
private URL registryUrl;
private ConsulRegistryFactory consulRegistryFactory;
@BeforeEach
public void setUp() {
Exception exception = null;
for (int i = 0; i < 10; i++) {
try {
this.consul = ConsulStarterBuilder.consulStarter()
.build()
.start();
} catch (Exception e) {
exception = e;
}
if (exception == null) {
break;
}
}
Assertions.assertNull(exception);
this.registryUrl = URL.valueOf("consul://localhost:" + consul.getHttpPort());
consulRegistryFactory = new ConsulRegistryFactory();
this.consulRegistry = (ConsulRegistry) consulRegistryFactory.createRegistry(registryUrl);
}
@AfterEach
public void tearDown() throws Exception {
consul.close();
this.consulRegistry.destroy();
}
@Test
public void testRegister() {
Set<URL> registered;
for (int i = 0; i < 2; i++) {
consulRegistry.register(serviceUrl);
registered = consulRegistry.getRegistered();
assertThat(registered.contains(serviceUrl), is(true));
}
registered = consulRegistry.getRegistered();
assertThat(registered.size(), is(1));
}
@Test
public void testSubscribe() {
NotifyListener listener = mock(NotifyListener.class);
consulRegistry.subscribe(serviceUrl, listener);
Map<URL, Set<NotifyListener>> subscribed = consulRegistry.getSubscribed();
assertThat(subscribed.size(), is(1));
assertThat(subscribed.get(serviceUrl).size(), is(1));
consulRegistry.unsubscribe(serviceUrl, listener);
subscribed = consulRegistry.getSubscribed();
assertThat(subscribed.size(), is(1));
assertThat(subscribed.get(serviceUrl).size(), is(0));
}
@Test
public void testAvailable() {
consulRegistry.register(serviceUrl);
assertThat(consulRegistry.isAvailable(), is(true));
// consulRegistry.destroy();
// assertThat(consulRegistry.isAvailable(), is(false));
}
@Test
public void testLookup() throws InterruptedException {
List<URL> lookup = consulRegistry.lookup(serviceUrl);
assertThat(lookup.size(), is(0));
consulRegistry.register(serviceUrl);
Thread.sleep(5000);
lookup = consulRegistry.lookup(serviceUrl);
assertThat(lookup.size(), is(1));
}
@Test
public void testStatusChecker() {
RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker();
Status status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.UNKNOWN));
Registry registry = consulRegistryFactory.getRegistry(registryUrl);
assertThat(registry, not(nullValue()));
status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
registry.register(serviceUrl);
status = registryStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
}
}
|
package netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Date;
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup group = new NioEventLoopGroup();
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringEncoder());
}
});
Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();
while (true){
channel.writeAndFlush(new Date()+":hello world");
Thread.sleep(2000);
}
}
}
|
/*
* Copyright 2011 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.gradle.plugins.ide.internal.tooling.idea;
import org.gradle.plugins.ide.internal.tooling.model.DefaultGradleProject;
import org.gradle.tooling.internal.gradle.DefaultProjectIdentifier;
import org.gradle.tooling.internal.gradle.GradleProjectIdentity;
import org.gradle.tooling.model.idea.IdeaCompilerOutput;
import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class DefaultIdeaModule implements Serializable, GradleProjectIdentity {
private String name;
private List<DefaultIdeaContentRoot> contentRoots = new LinkedList<DefaultIdeaContentRoot>();
private DefaultIdeaProject parent;
private List<DefaultIdeaDependency> dependencies = new LinkedList<DefaultIdeaDependency>();
private DefaultGradleProject gradleProject;
private IdeaCompilerOutput compilerOutput;
private DefaultIdeaJavaLanguageSettings javaLanguageSettings;
private String jdkName;
public String getName() {
return name;
}
public DefaultIdeaModule setName(String name) {
this.name = name;
return this;
}
public Collection<DefaultIdeaContentRoot> getContentRoots() {
return contentRoots;
}
public DefaultIdeaModule setContentRoots(List<DefaultIdeaContentRoot> contentRoots) {
this.contentRoots = contentRoots;
return this;
}
public DefaultIdeaProject getParent() {
return parent;
}
public DefaultIdeaProject getProject() {
return parent;
}
public DefaultIdeaModule setParent(DefaultIdeaProject parent) {
this.parent = parent;
return this;
}
public Collection<DefaultIdeaDependency> getDependencies() {
return dependencies;
}
public DefaultIdeaModule setDependencies(List<DefaultIdeaDependency> dependencies) {
this.dependencies = dependencies;
return this;
}
public Collection<Object> getChildren() {
return Collections.emptySet();
}
public String getDescription() {
return null;
}
public DefaultGradleProject getGradleProject() {
return gradleProject;
}
public DefaultIdeaModule setGradleProject(DefaultGradleProject gradleProject) {
this.gradleProject = gradleProject;
return this;
}
public IdeaCompilerOutput getCompilerOutput() {
return compilerOutput;
}
public DefaultIdeaModule setCompilerOutput(IdeaCompilerOutput compilerOutput) {
this.compilerOutput = compilerOutput;
return this;
}
public DefaultIdeaJavaLanguageSettings getJavaLanguageSettings() {
return javaLanguageSettings;
}
public DefaultIdeaModule setJavaLanguageSettings(DefaultIdeaJavaLanguageSettings javaLanguageSettings) {
this.javaLanguageSettings = javaLanguageSettings;
return this;
}
public String getJdkName() {
return jdkName;
}
public DefaultIdeaModule setJdkName(String jdkName) {
this.jdkName = jdkName;
return this;
}
public DefaultProjectIdentifier getProjectIdentifier() {
return gradleProject.getProjectIdentifier();
}
@Override
public String getProjectPath() {
return getProjectIdentifier().getProjectPath();
}
@Override
public File getRootDir() {
return getProjectIdentifier().getBuildIdentifier().getRootDir();
}
@Override
public String toString() {
return "IdeaModule{"
+ "name='" + name + '\''
+ ", gradleProject='" + gradleProject + '\''
+ ", contentRoots=" + contentRoots
+ ", compilerOutput=" + compilerOutput
+ ", dependencies count=" + dependencies.size()
+ '}';
}
}
|
/**
*
*/
package com.kant.datastructure.binarytrees;
import java.util.LinkedList;
import java.util.Stack;
/**
* @author shaskant
*
*/
public abstract class BinaryTree<T> {
protected TreeNode<T> root;
/**
*
*/
public BinaryTree() {
this(null);
}
/**
* start with a different tree
*
* @param node
*/
public BinaryTree(TreeNode<T> node) {
this.root = node;
}
public TreeNode<T> getRoot() {
return root;
}
public abstract boolean insert(T item);
public abstract boolean delete(T item);
public abstract boolean isPresent(T item);
/**
*
* @return
*/
public int getSize() {
return calcSize(root);
}
/**
* Size of a tree = Size of left subtree + 1 + Size of right subtree
*
* @param node
* @return
*/
private int calcSize(TreeNode<T> node) {
if (node != null) {
return 1 + calcSize(node.getLeft()) + calcSize(node.getRight());
}
return 0;
}
public int getHeightMax() {
return calcMaxHeight(root);
}
private int calcMaxHeight(TreeNode<T> node) {
if (node != null) {
return 1 + Math.max(calcMaxHeight(node.getLeft()),
calcMaxHeight(node.getRight()));
}
return 0;
}
private class TheHeight {
int value = 0;
}
/**
* calculates height along with the diameter<br/>
*
* Diameter of tree is defined as A longest path or route between any two
* nodes in a tree. The path may or may not for through the root.
* Maximum(Diameter of left subtree, Diameter of right subtree, Longest path
* between two nodes which passes through the root.)
*
* O(n)
*/
private int diameter(TreeNode<T> root, TheHeight theHeight) {
if (root == null) {
theHeight.value = 0;
return 0;
}
TheHeight lh = new TheHeight();
TheHeight rh = new TheHeight();
int ldiameter = diameter(root.getLeft(), lh);
int rdiameter = diameter(root.getRight(), rh);
theHeight.value = 1 + Math.max(lh.value, rh.value);
return Math
.max(lh.value + rh.value + 1, Math.max(ldiameter, rdiameter));
}
/**
* get diameter of tree.
*/
public int getDiameter() {
return diameter(root, new TheHeight());
}
/**
*
*/
public void traverseInOrder() {
inOrderDisplay(root);
}
/**
*
*/
public void traversePostOrder() {
postOrderDisplay(root);
}
/**
*
*/
public void traversePreOrder() {
preOrderDisplay(root);
}
/**
* Level order or BFS (recursive)
*/
public void traverseLevelOrder() {
System.out.println("Printing Level Order:");
for (int d = 0; d < getHeightMax(); d++) {
printThisLevel(getRoot(), d);
System.out.println();
}
}
private void printThisLevel(TreeNode<T> node, int d) {
if (node != null) {
if (d == 0) {
System.out.print(node.getData() + " ");
return;
} else if (d > 0) {
printThisLevel(node.getLeft(), d - 1);
printThisLevel(node.getRight(), d - 1);
}
}
}
/**
* iterative approach.[Single Queue approach]
*/
public void traverseLevelOrder2() {
System.out.println("using BFS to print level order:");
LinkedList<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
queue.add(root);
TreeNode<T> marker = new TreeNode<T>(null, null, null);
queue.add(marker);
int level = 0;
while (!queue.isEmpty()) {
System.out.print("\nAt " + level + ": ");
while (!isMarker(queue.peek())) {
TreeNode<T> curNode = queue.poll();
System.out.print(curNode.getData() + " ");
if (curNode.getLeft() != null)
queue.add(curNode.getLeft());
if (curNode.getRight() != null)
queue.add(curNode.getRight());
}
queue.poll();// remove marker
if (!queue.isEmpty()) {
level++;// increment level count
queue.add(marker);
}
}
}
private boolean isMarker(TreeNode<T> node) {
return node.getData() == null && node.getLeft() == null
&& node.getRight() == null;
}
/**
* @return
*/
public boolean isLeaf(TreeNode<T> node) {
return node.getLeft() == null && node.getRight() == null;
}
private void inOrderDisplay(TreeNode<T> node) {
if (node != null) {
inOrderDisplay(node.getLeft());
System.out.print(" " + node.getData() + " ");
inOrderDisplay(node.getRight());
}
}
private void postOrderDisplay(TreeNode<T> node) {
if (node != null) {
postOrderDisplay(node.getLeft());
postOrderDisplay(node.getRight());
System.out.print(" " + node.getData());
}
}
private void preOrderDisplay(TreeNode<T> node) {
if (node != null) {
System.out.print(node.getData() + " ");
preOrderDisplay(node.getLeft());
preOrderDisplay(node.getRight());
}
}
/**
* to print left view of tree.
*/
public void printLeftView() {
leftViewUtil(root, 0);
}
private static int max_level = -1;
/**
* Recursive function to print left view
*
* change order from [left -> right] to [right -> left] it print right view
* of tree.
*
* @param node
* @param level
*/
private void leftViewUtil(TreeNode<T> node, int level) {
// Base Case
if (node == null)
return;
// If this is the first node of its level
if (max_level < level) {
System.out.print(" " + node.data);
max_level = level;
}
// Recur for left and right subtrees
leftViewUtil(node.getLeft(), level + 1);
leftViewUtil(node.getRight(), level + 1);
}
/**
* printing spirally
*/
public void printSpiral() {
System.out.print("\nPrinting spiral order: ");
Stack<TreeNode<T>> stack1 = new Stack<>();
Stack<TreeNode<T>> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()) {
System.out.println();
// L -> R
while (!stack1.isEmpty()) {
TreeNode<T> cur = stack1.pop();
System.out.print(cur.getData() + " ");
if (cur.getLeft() != null) {
stack2.push(cur.getLeft());
}
if (cur.getRight() != null) {
stack2.push(cur.getRight());
}
}
System.out.println();
// R->L
while (!stack2.isEmpty()) {
TreeNode<T> cur = stack2.pop();
System.out.print(cur.getData() + " ");
if (cur.getRight() != null) {
stack1.push(cur.getRight());
}
if (cur.getLeft() != null) {
stack1.push(cur.getLeft());
}
}
}
}
/**
* TODO
* http://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and
* -inorder/
*
* TO be used for build tree from InOrder and PreOrder traversal values.
*/
static int preIndex = 0;
/**
* Recursive function to construct binary of size 'len' from InOrder
* traversal in[] and PreOrder traversal pre[].
*
* Initial values of inStrt and inEnd should be 0 and len - 1. The function
* doesn't do any error checking for cases where inOrder and preOrder do not
* form a tree.
*/
public TreeNode<T> buildTree(T in[], T pre[], int inStrt, int inEnd) {
if (inStrt > inEnd)
return null;
/**
* Pick current node from PreOrder traversal using preIndex and
* increment preIndex
*/
TreeNode<T> tNode = new TreeNode<>(pre[preIndex++]);
/* If this node has no children then return */
if (inStrt == inEnd)
return tNode;
/**
* Else find the index of this node in InOrder traversal
*/
int inIndex = search(in, inStrt, inEnd, tNode.data);
/**
* Using index in InOrder traversal, construct left and right subtrees
*/
tNode.setLeft(buildTree(in, pre, inStrt, inIndex - 1));
tNode.setRight(buildTree(in, pre, inIndex + 1, inEnd));
return tNode;
}
/**
* Function to find index of value in arr[start...end] The function assumes
* that value is present in in[]
*/
private int search(T arr[], int strt, int end, T value) {
int i;
for (i = strt; i <= end; i++) {
if (arr[i].equals(value))
return i;
}
return i;
}
}
|
package uk.nhs.adaptors.pss.translator.task;
import static java.util.UUID.randomUUID;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static uk.nhs.adaptors.common.util.FileUtil.readResourceAsString;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.xml.bind.JAXBException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import uk.nhs.adaptors.common.service.MDCService;
import uk.nhs.adaptors.pss.translator.amqp.JmsReader;
import uk.nhs.adaptors.pss.translator.exception.AttachmentNotFoundException;
import uk.nhs.adaptors.pss.translator.exception.BundleMappingException;
import uk.nhs.adaptors.pss.translator.exception.InlineAttachmentProcessingException;
import uk.nhs.adaptors.pss.translator.mhs.model.InboundMessage;
import uk.nhs.adaptors.pss.translator.service.XPathService;
import java.text.ParseException;
@ExtendWith(MockitoExtension.class)
public class MhsQueueMessageHandlerTest {
private static final String NHS_NUMBER = "123456";
private static final String INBOUND_MESSAGE_STRING = "{hi i'm inbound message}";
private static final String EHR_EXTRACT_INTERACTION_ID = "RCMR_IN030000UK06";
private static final String ACKNOWLEDGEMENT_INTERACTION_ID = "MCCI_IN010000UK13";
private static final String OTHER_INTERACTION_ID = "COPC_IN000001UK01";
private static final String UNKNOWN_INTERACTION_ID = "RANDOM_IN000001UK01";
private static final String CONVERSATION_ID_PATH = "/Envelope/Header/MessageHeader/ConversationId";
private static final String INTERACTION_ID_PATH = "/Envelope/Header/MessageHeader/Action";
private static final String CONVERSATION_ID = randomUUID().toString();
@Mock
private ObjectMapper objectMapper;
@Mock
private JmsReader jmsReader;
@Mock
private XPathService xPathService;
@Mock
private Message message;
@Mock
private Document ebXmlDocument;
@Mock
private MDCService mdcService;
@Mock
private EhrExtractMessageHandler ehrExtractMessageHandler;
@Mock
private AcknowledgmentMessageHandler acknowledgmentMessageHandler;
@InjectMocks
private MhsQueueMessageHandler mhsQueueMessageHandler;
private InboundMessage inboundMessage;
@Test
public void handleEhrExtractMessageWithoutErrorsShouldReturnTrue()
throws
JsonProcessingException,
JAXBException,
InlineAttachmentProcessingException,
BundleMappingException,
AttachmentNotFoundException,
ParseException,
SAXException {
inboundMessage = new InboundMessage();
prepareMocks(EHR_EXTRACT_INTERACTION_ID);
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertTrue(result);
verify(mdcService).applyConversationId(CONVERSATION_ID);
verify(ehrExtractMessageHandler).handleMessage(inboundMessage, CONVERSATION_ID);
verifyNoInteractions(acknowledgmentMessageHandler);
}
@Test
public void handleEhrExtractMessageWhenEhrExtractMessageHandlerThrowsErrorShouldReturnFalse()
throws
JAXBException,
JsonProcessingException,
InlineAttachmentProcessingException,
BundleMappingException,
AttachmentNotFoundException,
ParseException,
SAXException {
inboundMessage = new InboundMessage();
prepareMocks(EHR_EXTRACT_INTERACTION_ID);
doThrow(new JAXBException("Nobody expects the spanish inquisition!"))
.when(ehrExtractMessageHandler).handleMessage(inboundMessage, CONVERSATION_ID);
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertFalse(result);
verify(mdcService).applyConversationId(CONVERSATION_ID);
verifyNoInteractions(acknowledgmentMessageHandler);
}
@Test
public void handleAcknowledgeMessageWithoutErrorsShouldReturnTrue() throws SAXException {
inboundMessage = new InboundMessage();
prepareMocks(ACKNOWLEDGEMENT_INTERACTION_ID);
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertTrue(result);
verify(mdcService).applyConversationId(CONVERSATION_ID);
verify(acknowledgmentMessageHandler).handleMessage(inboundMessage, CONVERSATION_ID);
verifyNoInteractions(ehrExtractMessageHandler);
}
@Test
public void handleAcknowledgeMessageWhenAcknowledgmentMessageHandlerThrowsErrorShouldReturnFalse() throws SAXException {
inboundMessage = new InboundMessage();
prepareMocks(ACKNOWLEDGEMENT_INTERACTION_ID);
doThrow(new SAXException("Nobody expects the spanish inquisition!"))
.when(acknowledgmentMessageHandler).handleMessage(inboundMessage, CONVERSATION_ID);
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertFalse(result);
verify(mdcService).applyConversationId(CONVERSATION_ID);
verify(acknowledgmentMessageHandler).handleMessage(inboundMessage, CONVERSATION_ID);
verifyNoInteractions(ehrExtractMessageHandler);
}
@Test
public void handleMessageWithUnsupportedInteractionIdShouldReturnTrue() {
inboundMessage = new InboundMessage();
prepareMocks(UNKNOWN_INTERACTION_ID);
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertTrue(result);
verify(mdcService).applyConversationId(CONVERSATION_ID);
verifyNoInteractions(acknowledgmentMessageHandler);
verifyNoInteractions(ehrExtractMessageHandler);
}
@Test
public void handleMessageWhenObjectMapperThrowsErrorShouldReturnFalse() throws JMSException, JsonProcessingException {
when(jmsReader.readMessage(message)).thenReturn(INBOUND_MESSAGE_STRING);
when(objectMapper.readValue(INBOUND_MESSAGE_STRING, InboundMessage.class)).thenThrow(new JsonMappingException(null, "hello"));
boolean result = mhsQueueMessageHandler.handleMessage(message);
assertFalse(result);
verifyNoInteractions(acknowledgmentMessageHandler);
verifyNoInteractions(ehrExtractMessageHandler);
verifyNoInteractions(mdcService);
}
@SneakyThrows
private void prepareMocks(String interactionId) {
String ebXmlString = "<xml>";
inboundMessage.setPayload(readInboundMessagePayloadFromFile());
inboundMessage.setEbXML(ebXmlString);
when(jmsReader.readMessage(message)).thenReturn(INBOUND_MESSAGE_STRING);
when(objectMapper.readValue(INBOUND_MESSAGE_STRING, InboundMessage.class)).thenReturn(inboundMessage);
when(xPathService.parseDocumentFromXml(ebXmlString)).thenReturn(ebXmlDocument);
when(xPathService.getNodeValue(ebXmlDocument, CONVERSATION_ID_PATH)).thenReturn(CONVERSATION_ID);
when(xPathService.getNodeValue(ebXmlDocument, INTERACTION_ID_PATH)).thenReturn(interactionId);
}
@SneakyThrows
private String readInboundMessagePayloadFromFile() {
return readResourceAsString("/xml/inbound_message_payload.xml").replace("{{nhsNumber}}", NHS_NUMBER);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.catalina.core.StandardServer;
/**
* <p><strong>ServerFactory</strong> allows the registration of the
* (singleton) <code>Server</code> instance for this JVM, so that it
* can be accessed independently of any existing reference to the
* component hierarchy. This is important for administration tools
* that are built around the internal component implementation classes.
*
* @author Craig R. McClanahan
*
*/
public class ServerFactory {
// ------------------------------------------------------- Static Variables
/**
* The singleton <code>Server</code> instance for this JVM.
*/
private static final AtomicReference<Server> server = new AtomicReference<Server>();
// --------------------------------------------------------- Public Methods
/**
* Return the singleton <code>Server</code> instance for this JVM.
*/
public static Server getServer() {
return getServer(true);
}
/**
* Return the singleton <code>Server</code> instance for this JVM.
*
* @param create
* <code>true</code> to create a server if none is available and
* always return a <code>Server</code> instance,
* <code>false</code> to peek the current value and return
* <code>null</code> if no server has been created
* @return Server instance or null
*/
@SuppressWarnings("unused")
public static Server getServer(boolean create) {
Server s = server.get();
if (s == null && create) {
// Note that StandardServer() constructor calls setServer()
new StandardServer();
s = server.get();
}
return s;
}
/**
* Set the singleton <code>Server</code> instance for this JVM. This
* method must <strong>only</strong> be called from a constructor of
* the (singleton) <code>Server</code> instance that is created for
* this execution of Catalina.
*
* @param theServer The new singleton instance
*/
public static void setServer(Server theServer) {
server.compareAndSet(null, theServer);
}
/**
* Clears the singleton <code>Server</code> instance for this JVM. Allows to
* run several instances of Tomcat sequentially in the same JVM. Unit tests
* use this feature.
*/
public static void clear() {
server.set(null);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.isis.core.specsupport.scenarios;
import java.util.List;
import java.util.Map;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.hamcrest.Description;
import org.jmock.api.Action;
import org.jmock.api.Invocation;
import org.apache.isis.applib.DomainObjectContainer;
/**
* Utility class to support the writing of unit-scope specs.
*
* <p>
* The {@link #finds(Class, Strategy)} provides an implementation of a JMock
* {@link Action} that can simulate searching for an object from a database, and
* optionally automatically creating a new one if {@link Strategy specified}.
*
* <p>
* If objects are created, then (mock) services are automatically injected. This is performed by
* searching for <tt>injectXxx()</tt> methods. The (mock) {@link DomainObjectContainer container}
* is also automatically injected, through the <tt>setXxx</tt> method.
*
* <p>
* Finally, note that the {@link #init(Object, String) init} hook method allows subclasses to
* customize the state of any objects created.
*
* @deprecated - with no replacement
*/
@Deprecated
public class InMemoryDB {
private final ScenarioExecution scenarioExecution;
public InMemoryDB(ScenarioExecution scenarioExecution) {
this.scenarioExecution = scenarioExecution;
}
public static class EntityId {
private final Class<?> type;
private final String id;
public EntityId(Class<?> type, String id) {
this.type = type;
this.id = id;
}
Class<?> getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InMemoryDB.EntityId other = (InMemoryDB.EntityId) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return "EntityId [type=" + type + ", id=" + id + "]";
}
}
private Map<InMemoryDB.EntityId, Object> objectsById = Maps.newHashMap();
/**
* Returns the object if exists, but will NOT instantiate a new one if not present.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T getNoCreate(final Class<T> cls, final String id) {
Class type = cls;
while(type != null) {
// search for this class and all superclasses
final InMemoryDB.EntityId entityId = new EntityId(cls, id);
final Object object = objectsById.get(entityId);
if(object != null) {
return (T) object;
}
type = type.getSuperclass();
}
return null;
}
/**
* Returns the object if exists, else will instantiate and save a new one if not present.
*
* <p>
* The new object will have services injected into it (through the {@link ScenarioExecution#injectServices(Object)})
* and will be initialized through the {@link #init(Object, String) init hook} method.
*/
@SuppressWarnings({ "unchecked" })
public <T> T getElseCreate(final Class<T> cls, final String id) {
final Object object = getNoCreate(cls, id);
if(object != null) {
return (T) object;
}
Object obj = instantiateAndInject(cls);
init(obj, id);
return put(cls, id, obj);
}
/**
* Put an object into the database.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> T put(final Class<T> cls, final String id, Object obj) {
Class type = cls;
// put for this class and all superclasses
while(type != null) {
final InMemoryDB.EntityId entityId = new EntityId(cls, id);
objectsById.put(entityId, obj);
type = type.getSuperclass();
}
return (T) obj;
}
private Object instantiateAndInject(Class<?> cls) {
try {
return scenarioExecution.injectServices(cls.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Returns a JMock {@link Action} to return an instance of the provided class.
*
* <p>
* If the object is not yet held in memory, it will be automatically created,
* as per {@link #getElseCreate(Class, String)}.
*
* <p>
* This {@link Action} can only be set for expectations to invoke a method
* accepting a single string argument. This string argument is taken to be an
* identifier for the object (and is used in the caching of that object in memory).
*/
public Action finds(final Class<?> cls) {
return new Action() {
@Override
public Object invoke(Invocation invocation) throws Throwable {
if(invocation.getParameterCount() != 1) {
throw new IllegalArgumentException("intended for action of findByXxx");
}
final Object argObj = invocation.getParameter(0);
if(!(argObj instanceof String)) {
throw new IllegalArgumentException("Argument must be a string");
}
String arg = (String) argObj;
return getElseCreate(cls, arg);
}
@Override
public void describeTo(Description description) {
description.appendText("finds an instance of " + cls.getName());
}
};
}
public <T> List<T> findAll(Class<T> cls) {
return find(cls, Predicates.<T>alwaysTrue());
}
@SuppressWarnings("unchecked")
public <T> List<T> find(Class<T> cls, Predicate<T> predicate) {
final List<T> list = Lists.newArrayList();
for (EntityId entityId : objectsById.keySet()) {
if(cls.isAssignableFrom(entityId.getType())) {
final T object = (T) objectsById.get(entityId);
if(predicate.apply(object)) {
list.add(object);
}
}
}
return list;
}
/**
* Hook to initialize if possible.
*
* <p>
* The provided string is usually taken to be some sort of unique identifier for the object
* (unique in the context of any given scenario, that is).
*/
protected void init(Object obj, String str) {
}
}
|
package cc.youchain.protocol.core.methods.response;
import cc.youchain.protocol.ObjectMapperFactory;
import cc.youchain.protocol.core.Response;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.IOException;
/**
* Validator object returned by:
* <ul>
* <li>you_validatorByMainAddress</li>
* </ul>
*/
public class YOUValidator extends Response<Validator> {
//
@Override
@JsonDeserialize(using = YOUValidator.ResponseDeserialiser.class)
public void setResult(Validator result) {
super.setResult(result);
}
public Validator getValidator() {
return this.getResult();
}
//
public static class ResponseDeserialiser extends JsonDeserializer<Validator> {
private ObjectReader objectReader = ObjectMapperFactory.getObjectReader();
@Override
public Validator deserialize(
JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) {
return objectReader.readValue(jsonParser, Validator.class);
} else {
return null; // null is wrapped by Optional in above getter
}
}
}
}
|
package com.kotyj.com.model;
import java.io.Serializable;
/**
* @author: lilingfei
* @description:
* @date: 2019/5/9
*/
public class ProvinceModel implements Serializable {
private String proId;
private String province;
private String cityId;
private String city;
public String getProId() {
return proId == null ? "" : proId;
}
public void setProId(String proId) {
this.proId = proId;
}
public String getProvince() {
return province == null ? "" : province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCityId() {
return cityId == null ? "" : cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCity() {
return city == null ? "" : city;
}
public void setCity(String city) {
this.city = city;
}
}
|
/*******************************************************************************
* Copyright [2015] [Onboard team of SERC, Peking University]
*
* 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.onboard.web.api.project;
import org.elevenframework.web.interceptor.Interceptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.onboard.service.security.ProjectPrivilegeService;
import com.onboard.service.security.interceptors.ProjectAdminRequired;
/**
* Project相关的Controller
*
* @author ruici, yewei
*/
@RequestMapping(value = "/{companyId}/projects")
@Controller
public class ProjectAdminManageController {
public static final Logger logger = LoggerFactory.getLogger(ProjectAdminManageController.class);
@Autowired
private ProjectPrivilegeService projectPrivilegeService;
@RequestMapping(value = "/{projectId}/admins/{userId}", method = RequestMethod.POST)
@Interceptors({ ProjectAdminRequired.class })
public ResponseEntity<Object> addAdminFromProject(@PathVariable("companyId") int companyId,
@PathVariable("projectId") int projectId, @PathVariable("userId") int userId) {
projectPrivilegeService.addProjectAdmin(userId, projectId);
return new ResponseEntity<Object>(HttpStatus.CREATED);
}
@RequestMapping(value = "/{projectId}/admins/{userId}", method = RequestMethod.DELETE)
@Interceptors({ ProjectAdminRequired.class })
public ResponseEntity<Object> removeAdminFromProject(@PathVariable int companyId, @PathVariable int projectId,
@PathVariable int userId) {
projectPrivilegeService.removeProjectAdmin(userId, projectId);
return new ResponseEntity<Object>(HttpStatus.CREATED);
}
}
|
package com.example.myallonesolution;
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);
}
}
|
/*
* Copyright (c) 2021, The UAPKI Project Authors.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sit.uapki.cert;
import com.sit.uapki.common.PkiTime;
public class Validity {
String notBefore;
String notAfter;
public PkiTime getNotBefore () {
return new PkiTime(notBefore);
}
public PkiTime getNotAfter () {
return new PkiTime(notAfter);
}
}
|
package com.burst.sdk.struct.hw;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : D:\HWPuSDK.h</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class PU_START_DECODE_INFO extends Structure {
/** \u901a\u9053\u53f7 */
public NativeLong ulChannelId;
/**
* \u89c6\u9891\u89e3\u7801\u7c7b\u578b<br>
* C type : PU_ENCODE_TYPE_E
*/
public int enVideoEncodeType;
/**
* \u97f3\u9891\u89e3\u7801\u7c7b\u578b<br>
* C type : PU_ENCODE_TYPE_E
*/
public int enAudioEncodeType;
/**
* \u521d\u59cb\u5316\u89e3\u7801\u4f20\u8f93\u534f\u8bae<br>
* C type : PU_PROTOCOL_TYPE_E
*/
public int enProtocolType;
/**
* SDK\u7684\u7aef\u53e3\u4fe1\u606f<br>
* C type : PU_PORT_INFO_S
*/
public PU_PORT_INFO stLocalPortInfo;
/**
* SDK\u7684\u5a92\u4f53IP<br>
* C type : CHAR[16]
*/
public byte[] szLocalMediaIp = new byte[16];
/**
* \u4f1a\u8bddID<br>
* C type : CHAR[32]
*/
public byte[] szSessionID = new byte[32];
/**
* \u4f1a\u8bddURL<br>
* C type : CHAR[256]
*/
public byte[] szSessionUrl = new byte[256];
/** C type : CHAR[32] */
public byte[] szReserve = new byte[32];
public PU_START_DECODE_INFO() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("ulChannelId", "enVideoEncodeType", "enAudioEncodeType", "enProtocolType", "stLocalPortInfo", "szLocalMediaIp", "szSessionID", "szSessionUrl", "szReserve");
}
/**
* @param ulChannelId \u901a\u9053\u53f7<br>
* @param enVideoEncodeType \u89c6\u9891\u89e3\u7801\u7c7b\u578b<br>
* C type : PU_ENCODE_TYPE_E<br>
* @param enAudioEncodeType \u97f3\u9891\u89e3\u7801\u7c7b\u578b<br>
* C type : PU_ENCODE_TYPE_E<br>
* @param enProtocolType \u521d\u59cb\u5316\u89e3\u7801\u4f20\u8f93\u534f\u8bae<br>
* C type : PU_PROTOCOL_TYPE_E<br>
* @param stLocalPortInfo SDK\u7684\u7aef\u53e3\u4fe1\u606f<br>
* C type : PU_PORT_INFO_S<br>
* @param szLocalMediaIp SDK\u7684\u5a92\u4f53IP<br>
* C type : CHAR[16]<br>
* @param szSessionID \u4f1a\u8bddID<br>
* C type : CHAR[32]<br>
* @param szSessionUrl \u4f1a\u8bddURL<br>
* C type : CHAR[256]<br>
* @param szReserve C type : CHAR[32]
*/
public PU_START_DECODE_INFO(NativeLong ulChannelId, int enVideoEncodeType, int enAudioEncodeType, int enProtocolType, PU_PORT_INFO stLocalPortInfo, byte szLocalMediaIp[], byte szSessionID[], byte szSessionUrl[], byte szReserve[]) {
super();
this.ulChannelId = ulChannelId;
this.enVideoEncodeType = enVideoEncodeType;
this.enAudioEncodeType = enAudioEncodeType;
this.enProtocolType = enProtocolType;
this.stLocalPortInfo = stLocalPortInfo;
if ((szLocalMediaIp.length != this.szLocalMediaIp.length))
throw new IllegalArgumentException("Wrong array size !");
this.szLocalMediaIp = szLocalMediaIp;
if ((szSessionID.length != this.szSessionID.length))
throw new IllegalArgumentException("Wrong array size !");
this.szSessionID = szSessionID;
if ((szSessionUrl.length != this.szSessionUrl.length))
throw new IllegalArgumentException("Wrong array size !");
this.szSessionUrl = szSessionUrl;
if ((szReserve.length != this.szReserve.length))
throw new IllegalArgumentException("Wrong array size !");
this.szReserve = szReserve;
}
public PU_START_DECODE_INFO(Pointer peer) {
super(peer);
}
public static class ByReference extends PU_START_DECODE_INFO implements Structure.ByReference {
};
public static class ByValue extends PU_START_DECODE_INFO implements Structure.ByValue {
};
}
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.logstash.execution;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;
import org.jruby.Ruby;
import org.jruby.RubyBasicObject;
import org.jruby.RubyClass;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
* JRuby extension that provides a class to keep track of listener and dispatch events to those.
* */
@JRubyClass(name = "EventDispatcher")
public final class EventDispatcherExt extends RubyBasicObject {
private static final long serialVersionUID = 1L;
private final Collection<IRubyObject> listeners = new CopyOnWriteArraySet<>();
private IRubyObject emitter;
public EventDispatcherExt(final Ruby runtime, final RubyClass metaClass) {
super(runtime, metaClass);
}
@JRubyMethod
public EventDispatcherExt initialize(final ThreadContext context, final IRubyObject emitter) {
this.emitter = emitter;
return this;
}
@JRubyMethod
public IRubyObject emitter() {
return emitter;
}
/**
* This operation is slow because we use a CopyOnWriteArrayList
* But the majority of the addition will be done at bootstrap time
* So add_listener shouldn't be called often at runtime.
* On the other hand the notification could be called really often.
* @param context ThreadContext
* @param listener Listener
* @return Nil
*/
@JRubyMethod(name = "add_listener")
public IRubyObject addListener(final ThreadContext context, final IRubyObject listener) {
return listeners.add(listener) ? context.tru : context.fals;
}
/**
* This operation is slow because we use a `CopyOnWriteArrayList` as the backend, instead of a
* ConcurrentHashMap, but since we are mostly adding stuff and iterating the `CopyOnWriteArrayList`
* should provide a better performance.
* See note on add_listener, this method shouldn't be called really often.
* @param context ThreadContext
* @param listener Listener
* @return True iff listener was actually removed
*/
@JRubyMethod(name = "remove_listener")
public IRubyObject removeListener(final ThreadContext context, final IRubyObject listener) {
return listeners.remove(listener) ? context.tru : context.fals;
}
@JRubyMethod(name = {"execute", "fire"}, required = 1, rest = true)
public IRubyObject fire(final ThreadContext context, final IRubyObject[] arguments) {
final String methodName = arguments[0].asJavaString();
final IRubyObject[] args = new IRubyObject[arguments.length];
args[0] = emitter;
System.arraycopy(arguments, 1, args, 1, arguments.length - 1);
listeners.forEach(listener -> {
if (listener.respondsTo(methodName)) {
listener.callMethod(context, methodName, args);
}
});
return context.nil;
}
}
|
package daggerok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ReactiveClientApplicationTests {
@Test
public void contextLoads() {}
}
|
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.sdo.model.dataobject;
import commonj.sdo.Property;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import junit.textui.TestRunner;
import org.eclipse.persistence.sdo.SDOProperty;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.exceptions.SDOException;
public class SDODataObjectGetDateWithIndexConversionTest extends SDODataObjectConversionTestCases {
public SDODataObjectGetDateWithIndexConversionTest(String name) {
super(name);
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.sdo.model.dataobject.SDODataObjectGetDateWithIndexConversionTest" };
TestRunner.main(arguments);
}
//1. purpose: getDate with Boolean property
public void testGetDateFromBoolean() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_BOOLEAN);
dataObject.set(property, true);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//2. purpose: getDate with Byte property
public void testGetDateFromByte() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_BYTE);
dataObject.set(property, new String("eee").getBytes()[0]);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//3. purpose: getDate with character property
public void testGetDateFromCharacter() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_CHARACTER);
dataObject.set(property, 'c');
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//4. purpose: getDate with Double Property
public void testGetDateFromDouble() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_DOUBLE);
double doubleValue =3;
dataObject.set(property, doubleValue);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//5. purpose: getDate with float Property
public void testGetDateFromFloat() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_FLOAT);
float floatValue = 3;
dataObject.set(property, floatValue);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//7. purpose: getDate with int Property
public void testGetDateFromInt() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_INT);
int intValue = 3;
dataObject.set(property, intValue);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//8. purpose: getDate with Defined long Property
public void testGetDateConversionFromDefinedLongProperty() {
// dataObject's type add boolean property
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_LONG);
long l = 12;
Date d = new Date(l);
dataObject.setLong(PROPERTY_INDEX, l);// add it to instance list
this.assertEquals(d, dataObject.getDate(PROPERTY_INDEX));
}
//9. purpose: getDate with Undefined Boolean Property
public void testGetDateConversionFromUnDefinedBooleanProperty() {
SDOProperty property = new SDOProperty(aHelperContext);
property.setName(PROPERTY_NAME);
property.setType(SDOConstants.SDO_BOOLEAN);
Object obj = dataObject.getDate(PROPERTY_INDEX);
assertNull(obj);
}
//10. purpose: getDate with short Property
public void testGetDateFromShort() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_SHORT);
short shortValue = 3;
dataObject.set(property, shortValue);
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//11. purpose: getDate with Defined String Property
public void testGetDateConversionFromDefinedStringProperty() {
// dataObject's type add int property
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_STRING);
Calendar controlCalendar = Calendar.getInstance();
controlCalendar.clear();
controlCalendar.set(Calendar.YEAR, 2001);
controlCalendar.set(Calendar.MONTH, 0);
controlCalendar.set(Calendar.DATE, 1);
controlCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = controlCalendar.getTime();
dataObject.setString(property, "2001-01-01");// add it to instance list
this.assertEquals(d, dataObject.getDate(PROPERTY_INDEX));
}
//12. purpose: getDate with Undefined string Property
public void testGetDateConversionFromUnDefinedStringProperty() {
SDOProperty property = new SDOProperty(aHelperContext);
property.setName(PROPERTY_NAME);
property.setType(SDOConstants.SDO_STRING);
Object obj = dataObject.getDate(PROPERTY_INDEX);
assertNull(obj);
}
//13. purpose: getDate with bytes property
public void testGetDateFromBytes() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_BYTES);
dataObject.set(property, new String("eee").getBytes());
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//14. purpose: getBoolean with decimal property
public void testGetDateFromDecimal() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_DECIMAL);
dataObject.set(property, new BigDecimal(11));
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//15. purpose: getDate with integer property
public void testGetDateFromInteger() {
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_INTEGER);
dataObject.set(property, new Integer(2));
try {
dataObject.getDate(PROPERTY_INDEX);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//16. purpose: getDate with Defined Date Property
public void testGetDateConversionFromDefinedDateProperty() {
// dataObject's type add int property
SDOProperty property = ((SDOProperty)type.getProperty(PROPERTY_NAME));
property.setType(SDOConstants.SDO_DATE);
long l = 12000;
Date d = new Date(l);
dataObject.setDate(PROPERTY_INDEX, d);// add it to instance list
this.assertEquals(d, dataObject.getDate(PROPERTY_INDEX));
}
//12. purpose: getDate with Undefined string Property
public void testGetDateConversionFromUnDefinedDateProperty() {
SDOProperty property = new SDOProperty(aHelperContext);
property.setName(PROPERTY_NAME);
property.setType(SDOConstants.SDO_DATE);
Object obj = dataObject.getDate(PROPERTY_INDEX);
assertNull(obj);
}
//purpose: getDate with nul value
public void testGetDateWithNullArgument() {
try {
int p = -1;
dataObject.getDate(p);
} catch (SDOException e) {
assertEquals(SDOException.PROPERTY_NOT_FOUND_AT_INDEX ,e.getErrorCode());
return;
}
fail("an SDOException should have occurred.");
}
}
|
package com.femto.ugershop.fragment;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.femto.ugershop.R;
import com.femto.ugershop.activity.Activity_GoodsDetails;
import com.femto.ugershop.appfinal.AppFinalUrl;
import com.femto.ugershop.application.MyApplication;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Contacts.Data;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Fragment_StoreDetails extends BaseFragment implements OnRefreshListener2<ListView> {
private PullToRefreshListView lv_product;
private MylvStoreAdapter adapter;
private DisplayImageOptions options;
private int myId;
private List<StoreDetails> storeDetails;
private String starttime = "";
private String endtime = "";
private MyBroadCase mbr;
private int pageSize = 10;
private int pageIndex = 1;
private boolean isend = false;
int size = 0;
private boolean isfirstbanner = true;
private int type = 0;
DecimalFormat df = new DecimalFormat("######0.00");
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
lv_product.onRefreshComplete();
break;
default:
break;
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_sroredetails, container, false);
mregisterReceiver();
initParams();
storeDetails = new ArrayList<StoreDetails>();
initView(view);
getData(0, "", "", 1, pageSize);
MobclickAgent.onResume(getActivity());
setPageStart("商城明细");
return view;
}
private void initParams() {
SharedPreferences sp = getActivity().getSharedPreferences("Login", getActivity().MODE_PRIVATE);
myId = sp.getInt("userId", 0);
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.tianc) // 在ImageView加载过程中显示图片
.showImageForEmptyUri(R.drawable.tianc) // image连接地址为空时
.showImageOnFail(R.drawable.tianc) // image加载失败
.cacheInMemory(true) // 加载图片时会在内存中加载缓存
.cacheOnDisc(true) // 加载图片时会在磁盘中加载缓存
// .displayer(new RoundedBitmapDisplayer(0)) //
// 设置用户加载图片task(这里是圆角图片显示)
.build();
}
private void mregisterReceiver() {
mbr = new MyBroadCase();
IntentFilter filter = new IntentFilter();
filter.addAction("com.search.storeoder.info");
getActivity().registerReceiver(mbr, filter);
}
class MyBroadCase extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("zuo收到广播");
if (action.equals("com.search.storeoder.info")) {
if (starttime != null && starttime.length() != 0) {
starttime = intent.getStringExtra("starttime");
endtime = intent.getStringExtra("endtime");
if (endtime == null) {
endtime = "";
}
if (starttime == null) {
starttime = "";
}
type = intent.getIntExtra("type", 0);
storeDetails.clear();
getData(type, starttime, endtime, 1, pageSize);
}
}
}
}
private static String format = "yyyy-MM-dd HH:mm:ss";
public static Date toDate(String date) throws Exception {
if (null == date) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(date);
}
private void getData(int status, String starttime, String endtime, int pageIndex1, int pageSize) {
RequestParams params = new RequestParams();
showProgressDialog("加载中...");
params.put("indent.user.id", myId);
if (status == 1) {
try {
params.put("indent.createDate", starttime + " 00:00:00");
params.put("indent.endDate", endtime + " 23:59:59");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
params.put("indent.status", status);
params.put("pageModel.pageIndex", pageIndex1);
params.put("pageModel.pageSize", pageSize);
System.out.println("zuo===params=" + params.toString());
params.put("token", MyApplication.token);
MyApplication.ahc.post(AppFinalUrl.usergetDesinProductDeails, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// TODO Auto-generated method stub
super.onSuccess(statusCode, headers, response);
dismissProgressDialog();
System.out.println("zuo===" + response.toString());
try {
JSONArray jsonArray = response.getJSONArray("List");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject j = jsonArray.getJSONObject(i);
String imgUrl = j.optString("imgUrl");
String createDate = j.optString("createDate");
String productName = j.optString("productName");
int price = j.optInt("price");
int count = j.optInt("count");
int productId = j.optInt("productId");
double percentage = j.optDouble("percentage");
storeDetails.add(new StoreDetails(imgUrl, createDate, productName, price, count, percentage, productId));
size++;
}
if (size == 10) {
pageIndex++;
isend = false;
} else {
isend = true;
}
size = 0;
lv_product.onRefreshComplete();
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void initView(View v) {
lv_product = (PullToRefreshListView) v.findViewById(R.id.lv_pustoredetails);
lv_product.setOnRefreshListener(this);
lv_product.setMode(Mode.BOTH);
adapter = new MylvStoreAdapter();
lv_product.setAdapter(adapter);
}
@Override
public void onHiddenChanged(boolean hidden) {
// TODO Auto-generated method stub
super.onHiddenChanged(hidden);
if (!hidden) {
MobclickAgent.onResume(getActivity());
setPageStart("商城明细");
} else {
MobclickAgent.onPause(getActivity());
setPageEnd("商城明细");
}
}
@Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
class MylvStoreAdapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return storeDetails == null ? 0 : storeDetails.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return storeDetails.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
MyHolder h;
if (v == null) {
h = new MyHolder();
v = View.inflate(getActivity(), R.layout.item_lv_odermg, null);
h.ll_store_hint = (LinearLayout) v.findViewById(R.id.ll_store_hint);
h.im_pic_show = (ImageView) v.findViewById(R.id.im_pic_show);
h.tv_time_store = (TextView) v.findViewById(R.id.tv_time_store);
h.tv_price_s = (TextView) v.findViewById(R.id.tv_price_s);
h.tv_count_s = (TextView) v.findViewById(R.id.tv_count_s);
h.tv_math_s = (TextView) v.findViewById(R.id.tv_math_s);
h.tv_nub_odermg = (TextView) v.findViewById(R.id.tv_nub_odermg);
h.tv_goods_name = (TextView) v.findViewById(R.id.tv_goods_name);
v.setTag(h);
} else {
h = (MyHolder) v.getTag();
}
h.tv_nub_odermg.setText("" + storeDetails.get(position).count);
h.ll_store_hint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_GoodsDetails.class);
intent.putExtra("title", storeDetails.get(position).productName);
intent.putExtra("productId", storeDetails.get(position).productId);
startActivity(intent);
}
});
h.tv_time_store.setText("" + storeDetails.get(position).createDate);
h.tv_price_s.setText("" + storeDetails.get(position).price);
h.tv_count_s.setText("" + storeDetails.get(position).count);
h.tv_goods_name.setText("" + storeDetails.get(position).productName);
h.tv_math_s
.setText(""
+ storeDetails.get(position).price
* storeDetails.get(position).count
+ "*"
+ storeDetails.get(position).percentage
* 100
+ "%="
+ df.format((storeDetails.get(position).price * storeDetails.get(position).count * storeDetails
.get(position).percentage)) + "元");
ImageLoader.getInstance().displayImage(AppFinalUrl.photoBaseUri + storeDetails.get(position).imgUrl, h.im_pic_show,
options);
return v;
}
}
class MyHolder {
LinearLayout ll_store_hint;
ImageView im_pic_show;
TextView tv_goods_name, tv_time_store, tv_price_s, tv_count_s, tv_math_s, tv_nub_odermg;
}
class StoreDetails {
String imgUrl, createDate, productName;
int price, count, productId;
double percentage;
public StoreDetails(String imgUrl, String createDate, String productName, int price, int count, double percentage,
int productId) {
super();
this.imgUrl = imgUrl;
this.createDate = createDate;
this.productName = productName;
this.price = price;
this.count = count;
this.percentage = percentage;
this.productId = productId;
}
}
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
storeDetails.clear();
type = 0;
getData(0, "", "", 1, pageSize);
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
if (isend) {
handler.sendEmptyMessage(1);
Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
} else {
getData(type, starttime, endtime, pageIndex, pageSize);
}
}
}
|
package com.prowidesoftware.swift.model.mx;
import com.prowidesoftware.swift.model.mx.dic.*;
import com.prowidesoftware.swift.model.mx.AbstractMX;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.prowidesoftware.swift.model.MxSwiftMessage;
import com.prowidesoftware.swift.model.mx.AbstractMX;
import com.prowidesoftware.swift.model.mx.MxRead;
import com.prowidesoftware.swift.model.mx.MxReadImpl;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Class for sese.034.001.05 ISO 20022 message.
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Document", propOrder = {
"sctiesFincgStsAdvc"
})
@XmlRootElement(name = "Document", namespace = "urn:iso:std:iso:20022:tech:xsd:sese.034.001.05")
public class MxSese03400105
extends AbstractMX
{
@XmlElement(name = "SctiesFincgStsAdvc", required = true)
protected SecuritiesFinancingStatusAdviceV05 sctiesFincgStsAdvc;
public final static transient String BUSINESS_PROCESS = "sese";
public final static transient int FUNCTIONALITY = 34;
public final static transient int VARIANT = 1;
public final static transient int VERSION = 5;
@SuppressWarnings("rawtypes")
public final static transient Class[] _classes = new Class[] {AcknowledgedAcceptedStatus10Choice.class, AcknowledgedAcceptedStatus7Choice.class, AcknowledgementReason2 .class, AcknowledgementReason3 .class, AcknowledgementReason3Choice.class, AcknowledgementReason4Choice.class, AcknowledgementReason5Code.class, ActiveCurrencyAndAmount.class, ActiveOrHistoricCurrencyAndAmount.class, AddressType2Code.class, AlternatePartyIdentification2 .class, AmountAndDirection4 .class, AmountAndDirection8 .class, BeneficialOwnership1Choice.class, BlockTrade1Choice.class, BlockTrade1Code.class, CancellationReason1 .class, CancellationReason5Choice.class, CancellationStatus8Choice.class, CancelledStatusReason9Code.class, CashSettlementSystem1Choice.class, CashSettlementSystem2Code.class, CentralCounterPartyEligibility1Choice.class, CreditDebitCode.class, DateAndDateTimeChoice.class, DateCode1Choice.class, DateType3Code.class, DateType4Code.class, DateType5Code.class, DeliveryReceiptType2Code.class, DeniedReason1 .class, DeniedReason3Choice.class, DeniedReason3Code.class, DeniedStatus5Choice.class, FailingReason2Code.class, FailingReason3 .class, FailingReason3Choice.class, FailingStatus3Choice.class, FinancialInstrumentQuantity1Choice.class, GenericIdentification19 .class, GenericIdentification20 .class, GenericIdentification21 .class, IdentificationSource3Choice.class, IdentificationType4Choice.class, MarketClientSide1Choice.class, MarketClientSideCode.class, MarketIdentification1Choice.class, MarketIdentification78 .class, MarketType2Code.class, MarketType3Choice.class, MatchingStatus20Choice.class, MxSese03400105 .class, NameAndAddress5 .class, NettingEligibility1Choice.class, NoReasonCode.class, OriginalAndCurrentQuantities1 .class, OtherIdentification1 .class, OwnershipLegalRestrictions1Code.class, PartyIdentification36Choice.class, PartyIdentification37Choice.class, PartyIdentification43Choice.class, PartyIdentification44Choice.class, PartyIdentification48 .class, PartyIdentificationAndAccount42 .class, PartyTextInformation1 .class, PendingProcessingReason1 .class, PendingProcessingReason1Choice.class, PendingProcessingReason1Code.class, PendingProcessingStatus4Choice.class, PendingReason1 .class, PendingReason1Choice.class, PendingReason1Code.class, PendingReason2 .class, PendingReason2Choice.class, PendingReason6Code.class, PendingStatus13Choice.class, PendingStatus15Choice.class, PostalAddress1 .class, ProcessingStatus38Choice.class, ProprietaryReason1 .class, ProprietaryStatusAndReason1 .class, Quantity6Choice.class, Rate2 .class, RateName1 .class, RateOrName1Choice.class, RateType1Code.class, RateType5Choice.class, ReceiveDelivery1Code.class, RejectionReason15Choice.class, RejectionReason18 .class, RejectionReason38Code.class, RejectionStatus14Choice.class, RepairReason2Choice.class, RepairReason3 .class, RepairReason5Code.class, RepairStatus6Choice.class, RepoCallAcknowledgementReason2Code.class, RepoCallRequestStatus5Choice.class, Restriction1Choice.class, SafekeepingPlace1Code.class, SafekeepingPlace3Code.class, SafekeepingPlaceFormat3Choice.class, SafekeepingPlaceTypeAndAnyBICIdentifier1 .class, SafekeepingPlaceTypeAndText3 .class, SecuritiesAccount13 .class, SecuritiesFinancingStatusAdviceV05 .class, SecuritiesFinancingTransactionDetails24 .class, SecuritiesFinancingTransactionType1Code.class, SecuritiesRTGS1Choice.class, SecurityIdentification14 .class, SettlementDate2Choice.class, SettlementDateCode2Choice.class, SettlementDetails73 .class, SettlementParties11 .class, SettlementStatus10Choice.class, SettlementSystemMethod1Choice.class, SettlementSystemMethod1Code.class, SettlementTransactionCondition5Code.class, SettlementTransactionCondition6Code.class, SettlementTransactionCondition7Choice.class, SettlingCapacity2Code.class, SettlingCapacity4Choice.class, SupplementaryData1 .class, SupplementaryDataEnvelope1 .class, TaxCapacityParty1Choice.class, TaxLiability1Code.class, TerminationDate2Choice.class, TradeDate1Choice.class, TradeDateCode1Choice.class, TransactionIdentifications1 .class, TypeOfIdentification1Code.class, UnmatchedReason10Code.class, UnmatchedReason12 .class, UnmatchedReason15Choice.class, UnmatchedStatus13Choice.class };
public final static transient String NAMESPACE = "urn:iso:std:iso:20022:tech:xsd:sese.034.001.05";
public MxSese03400105() {
super();
}
/**
* Creates the MX object parsing the parameter String with the XML content
*
*/
public MxSese03400105(final String xml) {
this();
MxSese03400105 tmp = parse(xml);
sctiesFincgStsAdvc = tmp.getSctiesFincgStsAdvc();
}
/**
* Creates the MX object parsing the raw content from the parameter MxSwiftMessage
*
*/
public MxSese03400105(final MxSwiftMessage mxSwiftMessage) {
this(mxSwiftMessage.message());
}
/**
* Gets the value of the sctiesFincgStsAdvc property.
*
* @return
* possible object is
* {@link SecuritiesFinancingStatusAdviceV05 }
*
*/
public SecuritiesFinancingStatusAdviceV05 getSctiesFincgStsAdvc() {
return sctiesFincgStsAdvc;
}
/**
* Sets the value of the sctiesFincgStsAdvc property.
*
* @param value
* allowed object is
* {@link SecuritiesFinancingStatusAdviceV05 }
*
*/
public MxSese03400105 setSctiesFincgStsAdvc(SecuritiesFinancingStatusAdviceV05 value) {
this.sctiesFincgStsAdvc = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String getBusinessProcess() {
return BUSINESS_PROCESS;
}
@Override
public int getFunctionality() {
return FUNCTIONALITY;
}
@Override
public int getVariant() {
return VARIANT;
}
@Override
public int getVersion() {
return VERSION;
}
/**
* Creates the MX object parsing the raw content from the parameter XML
*
*/
public static MxSese03400105 parse(String xml) {
return ((MxSese03400105) MxReadImpl.parse(MxSese03400105 .class, xml, _classes));
}
/**
* Creates the MX object parsing the raw content from the parameter XML with injected read implementation
* @since 9.0.1
*
* @param parserImpl an MX unmarshall implementation
*/
public static MxSese03400105 parse(String xml, MxRead parserImpl) {
return ((MxSese03400105) parserImpl.read(MxSese03400105 .class, xml, _classes));
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
@SuppressWarnings("rawtypes")
public Class[] getClasses() {
return _classes;
}
/**
* Creates an MxSese03400105 messages from its JSON representation.
* <p>
* For generic conversion of JSON into the corresponding MX instance
* see {@link AbstractMX#fromJson(String)}
*
* @since 7.10.2
*
* @param json a JSON representation of an MxSese03400105 message
* @return
* a new instance of MxSese03400105
*/
public final static MxSese03400105 fromJson(String json) {
return AbstractMX.fromJson(json, MxSese03400105 .class);
}
}
|
/*******************************************************************************
*
* Copyright 2015 Walmart, 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.oneops.transistor.service;
import com.oneops.cms.cm.domain.CmsCI;
import com.oneops.cms.cm.domain.CmsCIAttribute;
import com.oneops.cms.cm.domain.CmsCIRelation;
import com.oneops.cms.cm.service.CmsCmProcessor;
import com.oneops.cms.dj.domain.CmsRelease;
import com.oneops.cms.dj.domain.CmsRfcCI;
import com.oneops.cms.dj.domain.CmsRfcRelation;
import com.oneops.cms.dj.service.CmsCmRfcMrgProcessor;
import com.oneops.cms.dj.service.CmsRfcProcessor;
import com.oneops.cms.util.CmsError;
import com.oneops.transistor.domain.ManifestRfcContainer;
import com.oneops.transistor.domain.ManifestRfcRelationTriplet;
import com.oneops.transistor.domain.ManifestRootRfcContainer;
import com.oneops.transistor.exceptions.TransistorException;
import com.oneops.transistor.util.CloudUtil;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class ManifestManagerImpl implements ManifestManager {
private static final Logger logger = Logger.getLogger(ManifestManagerImpl.class);
private CmsCmProcessor cmProcessor;
private CmsRfcProcessor rfcProcessor;
private CmsCmRfcMrgProcessor cmRfcMrgProcessor;
private ManifestRfcBulkProcessor manifestRfcProcessor;
private TransUtil trUtil;
private CloudUtil cloudUtil;
private ExecutorService executorService;
private int timeoutInMilliSeconds;
private final static String BASE_REALIZED_IN = "base.RealizedIn";
private final static String MANIFEST_PLATFORM = "manifest.Platform";
private final static String MANIFEST_COMPOSED_OF = "manifest.ComposedOf";
private final static String CATALOG_PLATFORM = "catalog.Platform";
private final static String ACCOUNT_ASSEMBLY = "account.Assembly";
private final static String BASE_CONSUMES = "base.Consumes";
private final static String BASE_DEPLOYED_TO = "base.DeployedTo";
private final static String ACCOUNT_CLOUD = "account.Cloud";
private final static String RELEASE_STATE_OPEN = "open";
public void setTimeoutInMilliSeconds(int timeoutInMilliSeconds) {
this.timeoutInMilliSeconds = timeoutInMilliSeconds;
}
public void setCmRfcMrgProcessor(CmsCmRfcMrgProcessor cmRfcMrgProcessor) {
this.cmRfcMrgProcessor = cmRfcMrgProcessor;
}
public void setTrUtil(TransUtil trUtil) {
this.trUtil = trUtil;
}
public void setRfcProcessor(CmsRfcProcessor rfcProcessor) {
this.rfcProcessor = rfcProcessor;
}
public void setCmProcessor(CmsCmProcessor cmProcessor) {
this.cmProcessor = cmProcessor;
}
public void setManifestRfcProcessor(ManifestRfcBulkProcessor manifestRfcBulkProcessor) {
this.manifestRfcProcessor = manifestRfcBulkProcessor;
}
public ExecutorService getExecutorService() {
return executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
@Override
public long generateEnvManifest(long envId, String userId, Map<String, String> platModes) {
long t1 = System.currentTimeMillis();
String oldThreadName = Thread.currentThread().getName();
Thread.currentThread().setName(getProcessingThreadName(oldThreadName, envId));
List<CmsCIRelation> assemblyRels = cmProcessor.getToCIRelations(envId, BASE_REALIZED_IN, null, ACCOUNT_ASSEMBLY);
CmsCI assembly = getAssembly(envId, assemblyRels);
CmsCI env = getEnv(envId);
String nsPath = getManifestNsPath(env);
//check for openRelease
check4OpenRelease(env, nsPath);
Long nsId = trUtil.verifyAndCreateNS(nsPath);
logger.info("Created nsId " + nsId);
List<CmsCIRelation> designPlatRels = cmProcessor.getFromCIRelations(assembly.getCiId(), null, "ComposedOf", CATALOG_PLATFORM);
//we need to reset all pending deletions cis just in case there was one added back
cmProcessor.resetDeletionsByNs(nsPath);
// check for edge case scenario when there is new design platform with the same name as old one but different pack
long releaseId = checkPlatformPackCompliance(designPlatRels, env, nsPath, userId);
if (releaseId > 0) {
//stop any processing and return new release id
return releaseId;
}
final CountDownLatch latch = new CountDownLatch(designPlatRels.size());
List<Future<DesignCIManifestRfcTouple>> submittedFutureTasks = new ArrayList<>();
for (CmsCIRelation platRelation : designPlatRels) {
String availMode = getPlatformAvailabiltyMode(platModes, platRelation);
Future<DesignCIManifestRfcTouple> future = executorService.submit(new ManifestRfcProcessorTask(env, nsPath, userId, availMode, latch, platRelation));
submittedFutureTasks.add(future);
}
boolean allPlatsProcessed;
try {
allPlatsProcessed = latch.await(timeoutInMilliSeconds, TimeUnit.MILLISECONDS); //wait for all platform processing threads to finish with timeout of 10 mins
if (!allPlatsProcessed) {
logger.error("All platforms not processed within timeout duration of " + timeoutInMilliSeconds);
throw new TransistorException(CmsError.TRANSISTOR_OPEN_MANIFEST_RELEASE, "Failed to pull latest design for all platform within timeout duration of " + timeoutInMilliSeconds + " millis");
}
} catch (InterruptedException ie) {
for (Future<DesignCIManifestRfcTouple> job : submittedFutureTasks) {
job.cancel(true);
}
throw new TransistorException(CmsError.TRANSISTOR_OPEN_MANIFEST_RELEASE, "Design pull process interrupted. ");
}
Map<Long, CmsRfcCI> design2manifestPlatMap = new HashMap<>();
for (Future<DesignCIManifestRfcTouple> task : submittedFutureTasks) {
DesignCIManifestRfcTouple touple;
try {
touple = task.get();
processPlatformRfcs(touple.manifestPlatformRfcs, userId);
CmsRfcCI manifestPlatformRfc = touple.manifestPlatformRfcs.getManifestPlatformRfc();
logger.info("Finished working on =" + manifestPlatformRfc.getNsPath() + " release id = " + manifestPlatformRfc.getReleaseId());
design2manifestPlatMap.put(touple.designPlatCI, manifestPlatformRfc);
} catch (Exception e) {
logger.error("Error in pulling latest design for all platforms ", e);
throw new TransistorException(CmsError.TRANSISTOR_OPEN_MANIFEST_RELEASE, "Error in pulling latest design for all platforms ");
}
}
long t2 = System.currentTimeMillis();
check4MissingServices(design2manifestPlatMap);
logger.info("Check missing services for " + nsPath + " completed in " + (System.currentTimeMillis() - t2) + " millis ");
//now we need to process linkedTo relations
t2 = System.currentTimeMillis();
manifestRfcProcessor.processLinkedTo(design2manifestPlatMap, nsPath, userId);
logger.info("Process linked to " + nsPath + " completed in " + (System.currentTimeMillis() - t2) + " millis ");
//now lets delete old existing plats that do not exists in new manifest
t2 = System.currentTimeMillis();
manifestRfcProcessor.processDeletedPlatforms(design2manifestPlatMap.values(), env, nsPath, userId);
logger.info("Process deleted platforms " + nsPath + " completed in " + (System.currentTimeMillis() - t2) + " millis ");
//process global variables from design
t2 = System.currentTimeMillis();
manifestRfcProcessor.processGlobalVars(assembly.getCiId(), env, nsPath, userId);
logger.info("Process global vars for " + nsPath + " completed in " + (System.currentTimeMillis() - t2) + " millis ");
long envReleaseId = populateParentRelease(env, nsPath);
logger.info("Pull design for " + nsPath + " completed in " + (System.currentTimeMillis() - t1) + " millis (releaseId " + envReleaseId + ")");
List<CmsRelease> manifestReleases = rfcProcessor.getLatestRelease(nsPath, "open");
if (manifestReleases.size()>0) {
CmsRelease release = manifestReleases.get(0);
release.setDescription("Pull design completed in "+(System.currentTimeMillis() - t1) + " ms");
rfcProcessor.updateRelease(release);
}
return envReleaseId;
}
/**
*
* @param design2manifestPlatMap design manifest platform map.
*/
private void check4MissingServices(Map<Long, CmsRfcCI> design2manifestPlatMap) throws TransistorException{
//get CiIds to be checked for missing services
Set<Long> manifestPlatformIds = design2manifestPlatMap.entrySet().stream().map(t -> t.getValue().getCiId()).collect(Collectors.toSet());
cloudUtil.check4missingServices(manifestPlatformIds);
}
private String getManifestNsPath(CmsCI env) {
return env.getNsPath() + "/" + env.getCiName() + "/manifest";
}
private void check4OpenRelease(CmsCI env, String nsPath) {
if (hasOpenManifestRelease(nsPath)) {
String message = "This environment has an open release. It needs to be discarded or committed before the design pull: "
+ env.getNsPath() + "/" + env.getCiName();
logger.info(message);
throw new TransistorException(CmsError.TRANSISTOR_OPEN_MANIFEST_RELEASE, message);
}
}
private CmsCI getAssembly(long envId, List<CmsCIRelation> assemblyRels) {
CmsCI assembly = null;
if (assemblyRels.size() > 0) {
assembly = assemblyRels.get(0).getFromCi();
}
if (assembly == null) {
String error = "Can not get assembly for envId = " + envId;
logger.error(error);
throw new TransistorException(CmsError.TRANSISTOR_CANNOT_GET_ASSEMBLY, error);
}
return assembly;
}
private String getPlatformAvailabiltyMode(Map<String, String> platModes, CmsCIRelation platRelation) {
String availMode = null;
if (platModes != null) {
availMode = platModes.get(String.valueOf(platRelation.getToCiId()));
if (availMode != null && availMode.length()==0) {
availMode="default";
}
}
return availMode;
}
/**
*
* @param manifestPlatformRfcs
* @param userId
*/
private void processPlatformRfcs(ManifestRfcContainer manifestPlatformRfcs, String userId) {
long t1= System.currentTimeMillis();
/***** Handle root RFC and relations ******/
CmsRfcCI rootRfc = null;
if(manifestPlatformRfcs.getRootRfcRelTouple().getRfcCI() != null){
rootRfc = rfcProcessor.createAndfetchRfcCINoCheck(manifestPlatformRfcs.getRootRfcRelTouple().getRfcCI(), userId);
} else if (manifestPlatformRfcs.getManifestPlatformRfc().getRfcAction() != null){
rootRfc = rfcProcessor.createAndfetchRfcCINoCheck(manifestPlatformRfcs.getManifestPlatformRfc(), userId);
}else{
rootRfc = manifestPlatformRfcs.getManifestPlatformRfc();
}
if(rootRfc.getCiState() == null){
rootRfc.setCiState("default");
}
Context context = new Context();
context.user = userId;
context.nsPath = rootRfc.getReleaseNsPath();
context.nsId = rootRfc.getNsId();
for(CmsRfcRelation toRfcRelation : manifestPlatformRfcs.getRootRfcRelTouple().getToRfcRelation()){
toRfcRelation.setToCiId(rootRfc.getCiId());
toRfcRelation.setToRfcCi(rootRfc);
toRfcRelation.setToRfcId(safelong2Long(rootRfc.getRfcId()));
toRfcRelation.setReleaseId(context.ensureReleaseId());
toRfcRelation.setNsId(context.nsId);
// toRfcRelation.setValidated(true);
// toRfcRelation.setComments(generateComments(toRfcRelation));
rfcProcessor.createRfcRelationNoCheck(toRfcRelation, userId);
}
for(CmsRfcRelation fromRfcRelation : manifestPlatformRfcs.getRootRfcRelTouple().getFromRfcRelation()){
fromRfcRelation.setFromCiId(rootRfc.getCiId());
fromRfcRelation.setFromRfcCi(rootRfc);
fromRfcRelation.setFromRfcId(safelong2Long(rootRfc.getRfcId()));
fromRfcRelation.setReleaseId(context.ensureReleaseId());
fromRfcRelation.setNsId(context.nsId);
// fromRfcRelation.setValidated(true);
rfcProcessor.createRfcRelationNoCheck(fromRfcRelation, userId);
}
/**Handle DependsOn and other pack relations ***/
for(ManifestRfcRelationTriplet rfcRelTriplet : manifestPlatformRfcs.getRfcRelTripletList()){
CmsRfcRelation rfcRelation = rfcRelTriplet.getRfcRelation();
if(rfcRelation.getRfcAction() == null){rfcRelation.setRfcAction("add");}
CmsRfcCI toRfcCI = rfcRelTriplet.getToRfcCI();
if(toRfcCI != null){
if(toRfcCI.getRfcAction() == null){toRfcCI.setRfcAction("add");}
if(toRfcCI.getRfcId() == 0 && toRfcCI.getCiId() == 0){
manifestRfcProcessor.setCiId(toRfcCI);
toRfcCI.setReleaseId(context.ensureReleaseId());
toRfcCI.setNsId(context.nsId);;
toRfcCI = rfcProcessor.createAndfetchRfcCINoCheck(toRfcCI, userId);
}
rfcRelation.setToCiId(toRfcCI.getCiId());
rfcRelation.setToRfcId(safelong2Long(toRfcCI.getRfcId()));
rfcRelation.setToRfcCi(toRfcCI);
}
CmsRfcCI fromRfcCI = rfcRelTriplet.getFromRfcCI();
if(fromRfcCI != null){
if(fromRfcCI.getRfcAction() == null){fromRfcCI.setRfcAction("add");}
if(fromRfcCI.getRfcId() == 0 && fromRfcCI.getCiId() == 0){
manifestRfcProcessor.setCiId(fromRfcCI);
fromRfcCI.setReleaseId(context.ensureReleaseId());
fromRfcCI.setNsId(context.nsId);
fromRfcCI = rfcProcessor.createAndfetchRfcCINoCheck(fromRfcCI, userId);
}
rfcRelation.setFromCiId(fromRfcCI.getCiId());
rfcRelation.setFromRfcId(safelong2Long(fromRfcCI.getRfcId()));
rfcRelation.setFromRfcCi(fromRfcCI);
}
if("manifest.Entrypoint".equals(rfcRelation.getRelationName())){
rfcRelation.setFromCiId(rootRfc.getCiId());
rfcRelation.setFromRfcId(safelong2Long(rootRfc.getRfcId()));
rfcRelation.setFromRfcCi(rootRfc);
}
rfcRelation.setReleaseId(context.ensureReleaseId());
// rfcRelation.setValidated(true);
rfcRelation.setNsId(context.nsId);
// manifestRfcProcessor.setCiRelationId(rfcRelation);
rfcProcessor.createRfcRelationNoCheck(rfcRelation, userId);
}
/**Handle Requires relations ***/
for(ManifestRootRfcContainer rfcRelTouple:manifestPlatformRfcs.getRfcRelToupleList()){
CmsRfcCI newRfc;
if(rfcRelTouple.getRfcCI().getRfcId() == 0){
rfcRelTouple.getRfcCI().setReleaseId(context.ensureReleaseId());
rfcRelTouple.getRfcCI().setNsId(context.nsId);;
newRfc = rfcProcessor.createAndfetchRfcCINoCheck(rfcRelTouple.getRfcCI(), userId);
}else{
newRfc = rfcRelTouple.getRfcCI();
}
for(CmsRfcRelation rfcRel : rfcRelTouple.getToRfcRelation()){
if(rfcRel.getRfcAction() == null){
rfcRel.setRfcAction("add");
}
if("manifest.Requires".equals(rfcRel.getRelationName()) && rfcRel.getFromCiId() == 0){
rfcRel.setFromCiId(rootRfc.getCiId());
rfcRel.setFromRfcCi(rootRfc);
rfcRel.setFromRfcId(safelong2Long(rootRfc.getRfcId()));
}
rfcRel.setToCiId(newRfc.getCiId());
rfcRel.setToRfcId(safelong2Long(newRfc.getRfcId()));
rfcRel.setToRfcCi(newRfc);
rfcRel.setReleaseId(context.ensureReleaseId());
// rfcRel.setValidated(true);
rfcRel.setNsId(context.nsId);
rfcProcessor.createRfcRelationNoCheck(rfcRel, userId);
}
for(CmsRfcRelation rfcRel : rfcRelTouple.getFromRfcRelation()){
if(rfcRel.getRfcAction() == null){
rfcRel.setRfcAction("add");
}
if(rfcRel.getToCiId() == 0){
rfcRel.setToCiId(rootRfc.getCiId());
rfcRel.setToRfcCi(rootRfc);
rfcRel.setToRfcId(safelong2Long(rootRfc.getRfcId()));
}
rfcRel.setFromCiId(newRfc.getCiId());
rfcRel.setFromRfcId(safelong2Long(newRfc.getRfcId()));
rfcRel.setFromRfcCi(newRfc);
rfcRel.setReleaseId(context.ensureReleaseId());
// rfcRel.setValidated(true);
rfcRel.setNsId(context.nsId);
rfcProcessor.createRfcRelationNoCheck(rfcRel, userId);
}
}
for(CmsRfcCI rfc:manifestPlatformRfcs.getRfcList()){
rfc.setReleaseId(context.ensureReleaseId());
rfc.setNsId(context.nsId);
rfcProcessor.createRfcCINoCheck(rfc, userId);
}
for(CmsRfcRelation rfcRelation:manifestPlatformRfcs.getRfcRelationList()){
if(rfcRelation.getFromCiId() == 0){
//if("base.Consumes".equals(rfcRelation.getRelationName())){
rfcRelation.setFromCiId(rootRfc.getCiId());
rfcRelation.setFromRfcCi(rootRfc);
rfcRelation.setFromRfcId(safelong2Long(rootRfc.getRfcId()));
// }else{
// rfcRelation.setFromCiId(rootRfc.getCiId());
// rfcRelation.setFromRfcCi(rootRfc);
// }
}
if(rfcRelation.getRfcAction() == null){
rfcRelation.setRfcAction("add");
}
rfcRelation.setReleaseId(context.ensureReleaseId());
// rfcRelation.setValidated(true);
rfcRelation.setNsId(context.nsId);
rfcProcessor.createRfcRelationNoCheck(rfcRelation, userId);
}
for(long delCiId:manifestPlatformRfcs.getDeleteCiIdList()){
ManifestRfcBulkProcessor.Context manifestContext = manifestRfcProcessor.new Context();
manifestContext.user = userId;
manifestContext.nsPath = rootRfc.getReleaseNsPath();
manifestContext.processed = new ArrayList<>();
manifestRfcProcessor.requestCiDeleteCascadeNoRelsRfcs(delCiId, 0, manifestContext);
}
for(CmsCIRelation delRelation:manifestPlatformRfcs.getDeleteRelationList()){
cmRfcMrgProcessor.requestRelationDelete(delRelation.getCiRelationId(), userId);
}
long t2= System.currentTimeMillis();
logger.info(" processPlatformRfcs "+ manifestPlatformRfcs.getManifestPlatformRfc().getNsPath() +" completed in "+(t2-t1) );
}
private Long safelong2Long(long rfcId) {
return rfcId==0?null:rfcId;
}
private long checkPlatformPackCompliance(List<CmsCIRelation> designPlatRels , CmsCI env, String nsPath, String userId) {
List<CmsCIRelation> manifestPlatRels = cmProcessor.getFromCIRelations(env.getCiId(), MANIFEST_COMPOSED_OF,null, MANIFEST_PLATFORM);
Map<String,String> manifestPlatPacks = new HashMap<String,String>(manifestPlatRels.size());
for (CmsCIRelation manifestRel : manifestPlatRels) {
CmsCI plat = manifestRel.getToCi();
String key = getPlatNameAndVersion(plat);
String value = getSourcePackVersion(plat);
manifestPlatPacks.put(key, value);
}
long newReleaseId = 0;
for (CmsCIRelation designRel : designPlatRels) {
CmsCI dPlat = designRel.getToCi();
String key = getPlatNameAndVersion(dPlat);
String value = getSourcePackVersion(dPlat);
if (manifestPlatPacks.containsKey(key) && !value.equals(manifestPlatPacks.get(key))) {
String platNsPath = nsPath + "/" + dPlat.getCiName() + "/" + dPlat.getAttribute("major_version").getDfValue();
List<CmsRfcCI> mPlats = cmRfcMrgProcessor.getDfDjCi(platNsPath, MANIFEST_PLATFORM, dPlat.getCiName(), "dj");
if (mPlats.size()>0) {
newReleaseId = manifestRfcProcessor.deleteManifestPlatform(mPlats.get(0), userId);
}
}
}
return newReleaseId;
}
private String getPlatNameAndVersion(CmsCI plat) {
return plat.getCiName() + ":" + plat.getAttribute("major_version").getDjValue();
}
private String getSourcePackVersion(CmsCI plat) {
// pack version should be in semver format like 1.0.1 but in legacy packs it could be still just single number
// if the major version is different - we need to remove the old platform,
// if only minor and patch version are different we can do update inline
String[] packVersion = plat.getAttribute("version").getDjValue().split("\\.");
return plat.getAttribute("source").getDjValue() +
":" + plat.getAttribute("pack").getDjValue() +
":" + packVersion[0];
}
private boolean hasOpenManifestRelease(String nsPath) {
List<CmsRelease> manReleases = rfcProcessor.getLatestRelease(nsPath, null);
if (manReleases.size() >0 ) {
if ("open".equals(manReleases.get(0).getReleaseState())) {
return true;
}
}
return false;
}
private long populateParentRelease(CmsCI env, String nsPath) {
long releaseId = 0;
//if we got new release lets populate parent releaseid with latest design
CmsRelease manifestRelease = null;
List<CmsRelease> manifestReleases = rfcProcessor.getLatestRelease(nsPath, "open");
if (manifestReleases.size()>0) {
manifestRelease = manifestReleases.get(0);
} else {
List<CmsRelease> closedManifestReleases = rfcProcessor.getLatestRelease(nsPath, "closed");
if (closedManifestReleases.size()>0) {
manifestRelease = closedManifestReleases.get(0);
}
}
if (manifestRelease != null) {
releaseId = manifestRelease.getReleaseId();
List<CmsRelease> designReleases = rfcProcessor.getLatestRelease(env.getNsPath(), "closed");
if (designReleases.size() > 0) {
CmsRelease designRelease = designReleases.get(0);
manifestRelease.setParentReleaseId(designRelease.getReleaseId());
rfcProcessor.updateRelease(manifestRelease);
}
}
return releaseId;
}
@Override
public long activatePlatform(long platId, String userId) {
return manifestRfcProcessor.setPlatformActive(platId, userId);
}
private CmsCI getEnv(long envId) {
return cmProcessor.getCiById(envId);
}
@Override
public void updateCloudAdminStatus(long cloudId, long envId,
String adminstatus, String userId) {
manifestRfcProcessor.updateCloudAdminStatus(cloudId, envId, adminstatus, userId);
}
@Override
public long disablePlatforms(Set<Long> platformIds, String userId) {
long releaseId = 0;
for (long manifestPlatformId : platformIds) {
releaseId = manifestRfcProcessor.disablePlatform(manifestPlatformId, userId);
}
return releaseId;
}
@Override
public long enablePlatforms(Set<Long> platformIds, String userId) {
long releaseId = 0;
cloudUtil.check4missingServices(platformIds);
for (long manifestPlatformId : platformIds) {
releaseId = manifestRfcProcessor.enablePlatform(manifestPlatformId, userId);
}
return releaseId;
}
@Override
public long updateEnvClouds(long envId, List<CmsCIRelation> cloudRels, String userId) {
//for now we will handle just new clouds
List<CmsCIRelation> existingCloudRels = cmProcessor.getFromCIRelationsNaked(envId, BASE_CONSUMES, ACCOUNT_CLOUD);
Set<Long> existingCloudIds = new HashSet<Long>();
for (CmsCIRelation rel : existingCloudRels) {
existingCloudIds.add(rel.getToCiId());
}
boolean needUpdate = false;
for (CmsCIRelation requestRel : cloudRels) {
if (!existingCloudIds.contains(requestRel.getToCiId())) {
// this is new cloud lets add env->cloud rel
cmProcessor.createRelation(requestRel);
needUpdate = true;
} else {
cmProcessor.updateRelation(requestRel);
existingCloudIds.remove(requestRel.getToCiId());
}
}
if (!existingCloudIds.isEmpty()) {
//looks like we need to delete some clouds
//first lets see if we have any open releases
processCloudDeletions(envId, existingCloudIds);
}
if (needUpdate) {
CmsCI env = getEnv(envId);
String nsPath = getManifestNsPath(env);
List<CmsRfcRelation> compOfRels = cmRfcMrgProcessor.getFromCIRelations(envId, MANIFEST_COMPOSED_OF, MANIFEST_PLATFORM, "dj");
for (CmsRfcRelation compOfRel : compOfRels) {
CmsRfcCI platform = compOfRel.getToRfcCi();
String platNs = platform.getNsPath();
manifestRfcProcessor.processClouds(env, platform, platNs, nsPath, userId, null, null,null);
Set<String> missingSrvs = cloudUtil.getMissingServices(platform.getCiId());
if (missingSrvs.size() > 0) {
logger.info(">>>>> Not all services available for platform: " + platform.getCiName() + ", the missing services: " + missingSrvs.toString());
manifestRfcProcessor.disablePlatform(platform.getCiId(), userId);
}
logger.info("Done working on platform " + platform.getCiName());
}
return populateParentRelease(env, nsPath);
} else {
return 0;
}
}
private void processCloudDeletions(long envId, Set<Long> cloudsToRemove) {
//looks like we need to delete some clouds
//first lets see if we have any open releases
CmsCI env = getEnv(envId);
String manifestNsPath = getManifestNsPath(env);
String bomNsPath = env.getNsPath() + "/" + env.getCiName() + "/bom";
List<CmsRelease> manifestOpenReleases = rfcProcessor.getReleaseBy3(manifestNsPath, null, RELEASE_STATE_OPEN);
if (manifestOpenReleases.size()>0) {
//throw exception on open release
throw new TransistorException(CmsError.TRANSISTOR_OPEN_MANIFEST_RELEASE, "There is open release in this environment, you have to commit or discard before deleteing the clouds!");
}
List<CmsRelease> bomOpenReleases = rfcProcessor.getReleaseBy3(bomNsPath, null, RELEASE_STATE_OPEN);
if (bomOpenReleases.size()>0) {
//throw exception on open release
throw new TransistorException(CmsError.TRANSISTOR_OPEN_BOM_RELEASE, "There is open BOM release in this environment, you have to deploy or discard before deleteing the clouds!");
}
//if we still here lets check if there are any boms deployed to the clouds that user tries to remove
for (long cloidId : cloudsToRemove) {
long deployedToRelsCount = cmProcessor.getCountToCIRelationsByNS(cloidId, BASE_DEPLOYED_TO, null, null, bomNsPath, true);
if (deployedToRelsCount > 0) {
//throw exception that there are active boms
throw new TransistorException(CmsError.TRANSISTOR_BOM_INSTANCES_EXIST, "There are deployed instances in the cloud, please put the cloud in offline mode for every platform and deploy!");
}
}
//if everything cool, let remove Consumes relations from platforms and env
for (long cloidId : cloudsToRemove) {
List<CmsCIRelation> platformRels = cmProcessor.getFromCIRelationsNaked(envId, MANIFEST_COMPOSED_OF, MANIFEST_PLATFORM);
for (CmsCIRelation platRel : platformRels) {
List<CmsCIRelation> platformCloudRels = cmProcessor.getFromToCIRelations(platRel.getToCiId(), BASE_CONSUMES, cloidId);
for (CmsCIRelation platCloudRel : platformCloudRels) {
cmProcessor.deleteRelation(platCloudRel.getCiRelationId());
}
}
//now lets remove env consumes rel
List<CmsCIRelation> envCloudRels = cmProcessor.getFromToCIRelations(envId, BASE_CONSUMES, cloidId);
for (CmsCIRelation cloudRel : envCloudRels) {
cmProcessor.deleteRelation(cloudRel.getCiRelationId());
}
}
}
@Override
public void updatePlatformCloud(CmsRfcRelation cloudRel, String userId) {
manifestRfcProcessor.updatePlatfomCloudStatus(cloudRel, userId);
}
@Override
public void rollbackOpenRelease(long envId) {
CmsCI env = getEnv(envId);
String nsPath = getManifestNsPath(env);
List<CmsRelease> list = rfcProcessor.getLatestRelease(nsPath, "open");
if (list.size()>0) {
rfcProcessor.deleteRelease(list.get(0).getReleaseId());
}
}
private class ManifestRfcProcessorTask implements Callable<DesignCIManifestRfcTouple> {
private final CmsCI env;
private final String nsPath;
private final String userId;
private final String availMode;
private final CountDownLatch countDownLatch;
private CmsCIRelation platRelation;
ManifestRfcProcessorTask(CmsCI env, String nsPath, String userId, String availMode,
CountDownLatch countDownLatch, CmsCIRelation platRelation) {
super();
this.env = env;
this.nsPath = nsPath;
this.userId = userId;
this.availMode = availMode;
this.countDownLatch = countDownLatch;
this.platRelation = platRelation;
}
public DesignCIManifestRfcTouple call() {
String oldThreadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(getProcessingThreadName(oldThreadName,env.getCiId()));
ManifestRfcContainer manifestPlatformRfcs = manifestRfcProcessor.processPlatform(platRelation.getToCi(), env, nsPath, userId, availMode);
DesignCIManifestRfcTouple touple = new DesignCIManifestRfcTouple(platRelation.getToCi().getCiId(),manifestPlatformRfcs);
return touple;
} catch (Exception e){
e.printStackTrace();
logger.error(e, e);
throw e;
} finally {
countDownLatch.countDown();
Thread.currentThread().setName(oldThreadName);
}
}
}
private class DesignCIManifestRfcTouple {
private Long designPlatCI;
//private CmsRfcCI manifestRfc;
private ManifestRfcContainer manifestPlatformRfcs;
public DesignCIManifestRfcTouple(Long designPlatCI, ManifestRfcContainer manifestPlatformRfcs) {
super();
this.designPlatCI = designPlatCI;
this.manifestPlatformRfcs = manifestPlatformRfcs;
}
}
class Context {
String user;
String nsPath;
Long releaseId;
public long nsId;
private Long ensureReleaseId() {
if (releaseId == null) {
releaseId = rfcProcessor.getOpenReleaseIdByNs(nsPath, null, user);
}
return releaseId;
}
}
public void setCloudUtil(CloudUtil cloudUtil) {
this.cloudUtil=cloudUtil;
}
}
|
/*
* Copyright 2002-2015 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit4.rules;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.test.context.junit4.ClassLevelDisabledSpringRunnerTests;
/**
* This class is an extension of {@link ClassLevelDisabledSpringRunnerTests}
* that has been modified to use {@link SpringClassRule} and
* {@link SpringMethodRule}.
*
* @author Sam Brannen
* @since 4.2
*/
@RunWith(JUnit4.class)
public class ClassLevelDisabledSpringRuleTests extends ClassLevelDisabledSpringRunnerTests {
@ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
// All tests are in superclass.
}
|
package ShopApp;
import java.util.ArrayList;
/**
*
* @author Dale Morrell
*
* This class models the customer's purchased products
*
*/
public class PurchaseHistory
{
private ArrayList<Product> purchasedProducts = new ArrayList<Product>();
/**
*
* @param purchasedProducts = An ArrayList for Product objects
*
* Constructor; Supplies ArrayList of product objects
*
*/
public PurchaseHistory(ArrayList<Product> purchasedProducts)
{
this.purchasedProducts = purchasedProducts;
}
/**
*
* @return Returns an ArrayList of products purchased
*
* Gets ArrayList for purchased products
*
*/
public ArrayList<Product> getPurchasedProducts()
{
return this.purchasedProducts;
}
}
|
/*
* Copyright 2013 - 2018 Anton Tananaev (anton@traccar.org)
*
* 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.traccar.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.traccar.storage.QueryExtended;
import org.traccar.storage.QueryIgnore;
import org.traccar.helper.Hashing;
import org.traccar.storage.StorageName;
import java.util.Date;
@StorageName("tc_users")
public class User extends ExtendedModel {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String login;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email.trim();
}
private String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private boolean readonly;
public boolean getReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
}
private boolean administrator;
public boolean getAdministrator() {
return administrator;
}
public void setAdministrator(boolean administrator) {
this.administrator = administrator;
}
private String map;
public String getMap() {
return map;
}
public void setMap(String map) {
this.map = map;
}
private double latitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
private double longitude;
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
private int zoom;
public int getZoom() {
return zoom;
}
public void setZoom(int zoom) {
this.zoom = zoom;
}
private boolean twelveHourFormat;
public boolean getTwelveHourFormat() {
return twelveHourFormat;
}
public void setTwelveHourFormat(boolean twelveHourFormat) {
this.twelveHourFormat = twelveHourFormat;
}
private String coordinateFormat;
public String getCoordinateFormat() {
return coordinateFormat;
}
public void setCoordinateFormat(String coordinateFormat) {
this.coordinateFormat = coordinateFormat;
}
private boolean disabled;
public boolean getDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
private Date expirationTime;
public Date getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
private int deviceLimit;
public int getDeviceLimit() {
return deviceLimit;
}
public void setDeviceLimit(int deviceLimit) {
this.deviceLimit = deviceLimit;
}
private int userLimit;
public int getUserLimit() {
return userLimit;
}
public void setUserLimit(int userLimit) {
this.userLimit = userLimit;
}
private boolean deviceReadonly;
public boolean getDeviceReadonly() {
return deviceReadonly;
}
public void setDeviceReadonly(boolean deviceReadonly) {
this.deviceReadonly = deviceReadonly;
}
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
if (token != null && !token.isEmpty()) {
if (!token.matches("^[a-zA-Z0-9-]{16,}$")) {
throw new IllegalArgumentException("Illegal token");
}
this.token = token;
} else {
this.token = null;
}
}
private boolean limitCommands;
public boolean getLimitCommands() {
return limitCommands;
}
public void setLimitCommands(boolean limitCommands) {
this.limitCommands = limitCommands;
}
private String poiLayer;
private boolean disableReports;
public boolean getDisableReports() {
return disableReports;
}
public void setDisableReports(boolean disableReports) {
this.disableReports = disableReports;
}
public String getPoiLayer() {
return poiLayer;
}
public void setPoiLayer(String poiLayer) {
this.poiLayer = poiLayer;
}
@QueryIgnore
public String getPassword() {
return null;
}
@QueryIgnore
public void setPassword(String password) {
if (password != null && !password.isEmpty()) {
Hashing.HashingResult hashingResult = Hashing.createHash(password);
hashedPassword = hashingResult.getHash();
salt = hashingResult.getSalt();
}
}
private String hashedPassword;
@JsonIgnore
@QueryExtended
public String getHashedPassword() {
return hashedPassword;
}
public void setHashedPassword(String hashedPassword) {
this.hashedPassword = hashedPassword;
}
private String salt;
@JsonIgnore
@QueryExtended
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public boolean isPasswordValid(String password) {
return Hashing.validatePassword(password, hashedPassword, salt);
}
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DistanceSensor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.navigation.*;
@Autonomous(name = "Limberg_GyroSquare", group = "Redline")
public class Limberg_GyroSquare extends LinearOpMode{
public void runOpMode() {
// Declarations Begin
//Motors
DcMotor left = hardwareMap.dcMotor.get("front_left_motor");
DcMotor right = hardwareMap.dcMotor.get("front_right_motor");
DcMotor back_left = hardwareMap.dcMotor.get("back_left_motor");
DcMotor back_right = hardwareMap.dcMotor.get("back_right_motor");
Servo servo1 = hardwareMap.servo.get("back_servo");
left.setDirection(DcMotor.Direction.REVERSE);
right.setDirection(DcMotor.Direction.FORWARD);
back_left.setDirection(DcMotor.Direction.REVERSE);
back_right.setDirection(DcMotor.Direction.FORWARD);
//Sensors
ColorSensor colorSensor = hardwareMap.colorSensor.get("color_sensor");
DistanceSensor frontDistance = hardwareMap.get(DistanceSensor.class, "front_distance");
DistanceSensor leftDistance = hardwareMap.get(DistanceSensor.class, "left_distance");
DistanceSensor rightDistance = hardwareMap.get(DistanceSensor.class, "right_distance");
DistanceSensor backDistance = hardwareMap.get(DistanceSensor.class, "back_distance");
BNO055IMU imu = null;
Orientation angles = null;
ElapsedTime et = new ElapsedTime();
// Gyro
imu = hardwareMap.get(BNO055IMU.class, "imu");
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS;
imu.initialize(parameters);
angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZXY, AngleUnit.DEGREES);
//Telemetry
telemetry.addData("Gyro Reading", angles.firstAngle);
telemetry.addData("frontDistance", frontDistance.getDistance(DistanceUnit.CM));
telemetry.addData("leftDistance", leftDistance.getDistance(DistanceUnit.CM));
telemetry.addData("rightDistance", rightDistance.getDistance(DistanceUnit.CM));
telemetry.addData("backDistance", backDistance.getDistance(DistanceUnit.CM));
telemetry.update();
//Variables
int c = 0;
waitForStart();
while (opModeIsActive()) {
//Declarations end
//Program Body Begin
while (c < 4) {
int enc = right.getCurrentPosition();
telemetry.addData("Encoder", enc);
while (right.getCurrentPosition() < enc + 5000) {
telemetry.addData("flag", 1);
telemetry.update();
right.setPower(1);
left.setPower(1);
telemetry.update();
if (right.getCurrentPosition() >= enc + 5000) {
telemetry.addData("flag", 2);
telemetry.update();
right.setPower(0);
left.setPower(0);
turn90Degrees();
c++;
}
}
}
}
}
public void turn90Degrees() {
// Declarations Begin
//Motors
DcMotor left = hardwareMap.dcMotor.get("front_left_motor");
DcMotor right = hardwareMap.dcMotor.get("front_right_motor");
DcMotor back_left = hardwareMap.dcMotor.get("back_left_motor");
DcMotor back_right = hardwareMap.dcMotor.get("back_right_motor");
Servo servo1 = hardwareMap.servo.get("back_servo");
left.setDirection(DcMotor.Direction.REVERSE);
right.setDirection(DcMotor.Direction.FORWARD);
back_left.setDirection(DcMotor.Direction.REVERSE);
back_right.setDirection(DcMotor.Direction.FORWARD);
//Sensors
ColorSensor colorSensor = hardwareMap.colorSensor.get("color_sensor");
DistanceSensor frontDistance = hardwareMap.get(DistanceSensor.class, "front_distance");
DistanceSensor leftDistance = hardwareMap.get(DistanceSensor.class, "left_distance");
DistanceSensor rightDistance = hardwareMap.get(DistanceSensor.class, "right_distance");
DistanceSensor backDistance = hardwareMap.get(DistanceSensor.class, "back_distance");
BNO055IMU imu = null;
Orientation angles = null;
ElapsedTime et = new ElapsedTime();
int enc = right.getCurrentPosition();
// Gyro
imu = hardwareMap.get(BNO055IMU.class, "imu");
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS;
imu.initialize(parameters);
angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZXY, AngleUnit.DEGREES);
//Telemetry
telemetry.addData("Gyro Reading", angles.firstAngle);
telemetry.addData("frontDistance", frontDistance.getDistance(DistanceUnit.CM));
telemetry.addData("leftDistance", leftDistance.getDistance(DistanceUnit.CM));
telemetry.addData("rightDistance", rightDistance.getDistance(DistanceUnit.CM));
telemetry.addData("backDistance", backDistance.getDistance(DistanceUnit.CM));
telemetry.addData("Encoder", enc);
telemetry.update();
double target = angles.firstAngle+90;
double error= 90, P, I, D, kp = 0.4, kd = 0.1, ki = 0, integral = 0, derivative, correction, t, lastTime = 0, dt = 0.1, lastError = 90;
while (error>3) {
angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
t = (double)System.nanoTime() / 10;
dt = t - lastTime;
error = target - angles.firstAngle;
integral += (error * dt);
derivative = (error - lastError) / dt;
P = kp * error;
I = ki * integral;
D = kd * derivative;
correction = P + I + D;
right.setPower(correction);
left.setPower(-correction);
back_right.setPower(correction);
back_left.setPower(-correction);
telemetry.addData("dt", dt);
telemetry.addData("error", error);
telemetry.addData("correction", correction);
telemetry.addData("angle", angles.firstAngle);
telemetry.update();
lastTime = t;
lastError = error;
}
right.setPower(0);
left.setPower(0);
back_right.setPower(0);
back_left.setPower(0);
}
}
|
/*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.pantheon.ethereum.p2p.rlpx;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.createMutableLocalNode;
import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.createPeer;
import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.enode;
import static tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper.enodeBuilder;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
import tech.pegasys.pantheon.ethereum.p2p.config.RlpxConfiguration;
import tech.pegasys.pantheon.ethereum.p2p.discovery.DiscoveryPeer;
import tech.pegasys.pantheon.ethereum.p2p.peers.DefaultPeer;
import tech.pegasys.pantheon.ethereum.p2p.peers.EnodeURL;
import tech.pegasys.pantheon.ethereum.p2p.peers.MutableLocalNode;
import tech.pegasys.pantheon.ethereum.p2p.peers.Peer;
import tech.pegasys.pantheon.ethereum.p2p.peers.PeerProperties;
import tech.pegasys.pantheon.ethereum.p2p.peers.PeerTestHelper;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissions.Action;
import tech.pegasys.pantheon.ethereum.p2p.permissions.PeerPermissionsException;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.MockConnectionInitializer;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.MockPeerConnection;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.PeerConnection;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.PeerConnection.PeerNotConnected;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.connections.PeerConnectionEvents;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.Capability;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason;
import tech.pegasys.pantheon.ethereum.p2p.rlpx.wire.messages.PingMessage;
import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class RlpxAgentTest {
private static final KeyPair KEY_PAIR = KeyPair.generate();
private final RlpxConfiguration config = RlpxConfiguration.create();
private final TestPeerPermissions peerPermissions = spy(new TestPeerPermissions());
private final PeerProperties peerProperties = mock(PeerProperties.class);
private final MutableLocalNode localNode = createMutableLocalNode();
private final MetricsSystem metrics = new NoOpMetricsSystem();
private final PeerConnectionEvents peerConnectionEvents = new PeerConnectionEvents(metrics);
private final MockConnectionInitializer connectionInitializer =
new MockConnectionInitializer(peerConnectionEvents);
private RlpxAgent agent = agent();
@Before
public void setup() {
// Set basic defaults
when(peerProperties.ignoreMaxPeerLimits(any())).thenReturn(false);
config.setMaxPeers(5);
}
@Test
public void start() {
// Initial call to start should work
final CompletableFuture<Integer> future = agent.start();
assertThat(future).isDone();
assertThat(future).isNotCompletedExceptionally();
// Subsequent call to start should fail
final CompletableFuture<Integer> future2 = agent.start();
assertThat(future2).isDone();
assertThat(future2).isCompletedExceptionally();
assertThatThrownBy(future2::get)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unable to start an already started");
}
@Test
public void stop() throws ExecutionException, InterruptedException {
// Cannot stop before starting
final CompletableFuture<Void> future = agent.stop();
assertThat(future).isDone();
assertThat(future).isCompletedExceptionally();
assertThatThrownBy(future::get)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageContaining("Illegal attempt to stop");
// Stop after starting should succeed
startAgent();
final MockPeerConnection connection = (MockPeerConnection) agent.connect(createPeer()).get();
final CompletableFuture<Void> future2 = agent.stop();
assertThat(future2).isDone();
assertThat(future2).isNotCompletedExceptionally();
// Check peer was disconnected
assertThat(connection.getDisconnectReason()).contains(DisconnectReason.CLIENT_QUITTING);
// Cannot stop again
final CompletableFuture<Void> future3 = agent.stop();
assertThat(future3).isDone();
assertThat(future3).isCompletedExceptionally();
assertThatThrownBy(future3::get)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageContaining("Illegal attempt to stop");
}
@Test
public void connect_succeeds() {
startAgent();
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isNotCompletedExceptionally();
assertThat(agent.getPeerConnection(peer)).contains(connection);
}
@Test
public void connect_fails() {
connectionInitializer.setAutocompleteConnections(false);
startAgent();
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
// Fail connection
connection.completeExceptionally(new RuntimeException("whoopsies"));
assertPeerConnectionNotTracked(peer);
}
@Test
public void connect_toDiscoveryPeerUpdatesStats() {
startAgent();
final DiscoveryPeer peer = DiscoveryPeer.fromEnode(enode());
assertThat(peer.getLastAttemptedConnection()).isEqualTo(0);
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isNotCompletedExceptionally();
assertThat(peer.getLastAttemptedConnection()).isGreaterThan(0);
}
@Test
public void incomingConnect_succeeds() {
startAgent();
final Peer peer = createPeer();
final PeerConnection connection = connection(peer);
connectionInitializer.simulateIncomingConnection(connection);
final Optional<CompletableFuture<PeerConnection>> trackedConnection =
agent.getPeerConnection(peer);
assertThat(trackedConnection).isNotEmpty();
assertThat(trackedConnection.get()).isCompletedWithValue(connection);
}
@Test
public void connect_failsIfAgentIsNotReady() {
// Don't start agent or set localNode
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isCompletedExceptionally();
assertThatThrownBy(connection::get)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageContaining("Cannot connect before")
.hasMessageContaining("has finished starting");
assertPeerConnectionNotTracked(peer);
}
@Test
public void incomingConnect_failsIfAgentIsNotReady() {
// Don't start agent or set localNode
final Peer peer = createPeer();
final PeerConnection connection = connection(peer);
connectionInitializer.simulateIncomingConnection(connection);
assertPeerConnectionNotTracked(peer);
assertThat(agent.getConnectionCount()).isEqualTo(0);
}
@Test
public void connect_failsIfPeerIsNotListening() {
startAgent();
final Peer peer = DefaultPeer.fromEnodeURL(enodeBuilder().disableListening().build());
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isCompletedExceptionally();
assertThatThrownBy(connection::get)
.hasCauseInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Attempt to connect to peer with no listening port");
assertPeerConnectionNotTracked(peer);
}
@Test
public void connect_doesNotCreateDuplicateConnections() {
startAgent();
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> connection1 = agent.connect(peer);
final CompletableFuture<PeerConnection> connection2 = agent.connect(peer);
assertThat(connection2).isDone();
assertThat(connection2).isNotCompletedExceptionally();
assertThat(connection2).isEqualTo(connection1);
assertThat(agent.getPeerConnection(peer)).contains(connection2);
assertThat(agent.getConnectionCount()).isEqualTo(1);
}
@Test
public void incomingConnection_deduplicatedWhenAlreadyConnected_peerWithHigherValueNodeId() {
final BytesValue localNodeId = BytesValue.fromHexString("0x01", EnodeURL.NODE_ID_SIZE);
final BytesValue remoteNodeId = BytesValue.fromHexString("0x02", EnodeURL.NODE_ID_SIZE);
startAgent(localNodeId);
final Peer peer = createPeer(remoteNodeId);
final CompletableFuture<PeerConnection> existingConnection = agent.connect(peer);
final MockPeerConnection incomingConnection = connection(peer);
connectionInitializer.simulateIncomingConnection(incomingConnection);
// Existing connection should be kept
assertThat(agent.getPeerConnection(peer)).contains(existingConnection);
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(incomingConnection.isDisconnected()).isTrue();
assertThat(incomingConnection.getDisconnectReason())
.contains(DisconnectReason.ALREADY_CONNECTED);
}
@Test
public void incomingConnection_deduplicatedWhenAlreadyConnected_peerWithLowerValueNodeId()
throws ExecutionException, InterruptedException {
final BytesValue localNodeId = BytesValue.fromHexString("0x02", EnodeURL.NODE_ID_SIZE);
final BytesValue remoteNodeId = BytesValue.fromHexString("0x01", EnodeURL.NODE_ID_SIZE);
startAgent(localNodeId);
final Peer peer = createPeer(remoteNodeId);
final CompletableFuture<PeerConnection> existingConnection = agent.connect(peer);
final PeerConnection incomingConnection = connection(peer);
connectionInitializer.simulateIncomingConnection(incomingConnection);
// New connection should be kept
assertThat(agent.getPeerConnection(peer).get().get()).isEqualTo(incomingConnection);
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(existingConnection.get().isDisconnected()).isTrue();
assertThat(((MockPeerConnection) existingConnection.get()).getDisconnectReason())
.contains(DisconnectReason.ALREADY_CONNECTED);
}
@Test
public void connect_failsWhenMaxPeersConnected() {
// Saturate connections
startAgentWithMaxPeers(1);
agent.connect(createPeer());
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isCompletedExceptionally();
assertThatThrownBy(connection::get)
.hasCauseInstanceOf(IllegalStateException.class)
.hasMessageContaining("Max peer peer connections established (1). Cannot connect to peer");
assertPeerConnectionNotTracked(peer);
assertThat(agent.getConnectionCount()).isEqualTo(1);
}
@Test
public void incomingConnection_maxPeersExceeded()
throws ExecutionException, InterruptedException {
// Saturate connections
startAgentWithMaxPeers(1);
final Peer existingPeer = createPeer();
final PeerConnection existingConnection = agent.connect(existingPeer).get();
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(1);
// Simulate incoming connection
final Peer newPeer = createPeer();
final MockPeerConnection incomingConnection = connection(newPeer);
connectionInitializer.simulateIncomingConnection(incomingConnection);
// Incoming or existing connection should be disconnected
assertThat(agent.getConnectionCount()).isEqualTo(1);
if (agent.getPeerConnection(newPeer).isPresent()) {
assertThat(((MockPeerConnection) existingConnection).getDisconnectReason())
.contains(DisconnectReason.TOO_MANY_PEERS);
} else {
assertThat(incomingConnection.getDisconnectReason())
.contains(DisconnectReason.TOO_MANY_PEERS);
}
}
@Test
public void connect_succeedsForExemptPeerWhenMaxPeersConnected()
throws ExecutionException, InterruptedException {
// Turn off autocomplete so that each connection is established (completed) after it has been
// successfully added to the internal connections set. This mimics async production behavior.
connectionInitializer.setAutocompleteConnections(false);
// Saturate connections
startAgentWithMaxPeers(1);
final CompletableFuture<PeerConnection> existingConnectionFuture = agent.connect(createPeer());
connectionInitializer.completePendingFutures();
final MockPeerConnection existingConnection =
(MockPeerConnection) existingConnectionFuture.get();
final Peer peer = createPeer();
when(peerProperties.ignoreMaxPeerLimits(peer)).thenReturn(true);
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
connectionInitializer.completePendingFutures();
assertThat(connection).isDone();
assertThat(connection).isNotCompletedExceptionally();
assertThat(agent.getPeerConnection(peer)).contains(connection);
// Previous, non-exempt connection should be disconnected
assertThat(existingConnection.isDisconnected()).isTrue();
assertThat(existingConnection.getDisconnectReason()).contains(DisconnectReason.TOO_MANY_PEERS);
assertThat(agent.getConnectionCount()).isEqualTo(1);
}
@Test
public void connect_succeedsForExemptPeerWhenMaxExemptPeersConnected() {
// Turn off autocomplete so that each connection is established (completed) after it has been
// successfully added to the internal connections set. This mimics async production behavior.
connectionInitializer.setAutocompleteConnections(false);
startAgentWithMaxPeers(1);
final Peer peerA = createPeer();
final Peer peerB = createPeer();
when(peerProperties.ignoreMaxPeerLimits(peerA)).thenReturn(true);
when(peerProperties.ignoreMaxPeerLimits(peerB)).thenReturn(true);
// Saturate connections
final CompletableFuture<PeerConnection> existingConnection = agent.connect(peerA);
connectionInitializer.completePendingFutures();
// Create new connection
final CompletableFuture<PeerConnection> connection = agent.connect(peerB);
connectionInitializer.completePendingFutures();
assertThat(connection).isDone();
assertThat(connection).isNotCompletedExceptionally();
// Both connections should be kept since they are both exempt from max peer limits
assertThat(agent.getPeerConnection(peerA)).contains(existingConnection);
assertThat(agent.getPeerConnection(peerB)).contains(connection);
assertThat(agent.getConnectionCount()).isEqualTo(2);
}
@Test
public void incomingConnection_maxPeersExceeded_incomingConnectionExemptFromLimits()
throws ExecutionException, InterruptedException {
final Peer peerA = createPeer();
final Peer peerB = createPeer();
when(peerProperties.ignoreMaxPeerLimits(peerB)).thenReturn(true);
// Saturate connections
startAgentWithMaxPeers(1);
// Add existing peer
final MockPeerConnection existingConnection = (MockPeerConnection) agent.connect(peerA).get();
assertThat(agent.getConnectionCount()).isEqualTo(1);
// Simulate incoming connection
final MockPeerConnection connection = connection(peerB);
connectionInitializer.simulateIncomingConnection(connection);
// Existing connection should be disconnected
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertPeerConnectionNotTracked(peerA);
assertThat(agent.getPeerConnection(peerB)).isNotEmpty();
assertThat(existingConnection.isDisconnected()).isTrue();
assertThat(existingConnection.getDisconnectReason()).contains(DisconnectReason.TOO_MANY_PEERS);
assertThat(connection.isDisconnected()).isFalse();
}
@Test
public void incomingConnection_maxPeersExceeded_existingConnectionExemptFromLimits()
throws ExecutionException, InterruptedException {
final Peer peerA = createPeer();
final Peer peerB = createPeer();
when(peerProperties.ignoreMaxPeerLimits(peerA)).thenReturn(true);
// Saturate connections
startAgentWithMaxPeers(1);
// Add existing peer
final PeerConnection existingConnection = agent.connect(peerA).get();
assertThat(agent.getConnectionCount()).isEqualTo(1);
// Simulate incoming connection
final MockPeerConnection connection = connection(peerB);
connectionInitializer.simulateIncomingConnection(connection);
// Incoming connection should be disconnected
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertPeerConnectionNotTracked(peerB);
assertThat(agent.getPeerConnection(peerA)).isNotEmpty();
assertThat(connection.isDisconnected()).isTrue();
assertThat(connection.getDisconnectReason()).contains(DisconnectReason.TOO_MANY_PEERS);
assertThat(existingConnection.isDisconnected()).isFalse();
}
@Test
public void incomingConnection_maxPeersExceeded_allConnectionsExemptFromLimits()
throws ExecutionException, InterruptedException {
final Peer peerA = createPeer();
final Peer peerB = createPeer();
when(peerProperties.ignoreMaxPeerLimits(peerA)).thenReturn(true);
when(peerProperties.ignoreMaxPeerLimits(peerB)).thenReturn(true);
// Saturate connections
startAgentWithMaxPeers(1);
// Add existing peer
final CompletableFuture<PeerConnection> existingConnection = agent.connect(peerA);
assertThat(agent.getConnectionCount()).isEqualTo(1);
// Simulate incoming connection
final PeerConnection connection = connection(peerB);
connectionInitializer.simulateIncomingConnection(connection);
// Neither peer should be disconnected
assertThat(agent.getConnectionCount()).isEqualTo(2);
assertThat(agent.getPeerConnection(peerB)).isNotEmpty();
assertThat(agent.getPeerConnection(peerA)).isNotEmpty();
assertThat(connection.isDisconnected()).isFalse();
assertThat(existingConnection.get().isDisconnected()).isFalse();
}
@Test
public void connect_failsIfPeerIsNotPermitted() {
startAgent();
final Peer peer = createPeer();
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()), eq(peer), eq(Action.RLPX_ALLOW_NEW_OUTBOUND_CONNECTION));
final CompletableFuture<PeerConnection> connection = agent.connect(peer);
assertThat(connection).isDone();
assertThat(connection).isCompletedExceptionally();
assertThatThrownBy(connection::get).hasCauseInstanceOf(PeerPermissionsException.class);
assertPeerConnectionNotTracked(peer);
}
@Test
public void incomingConnection_disconnectedIfPeerIsNotPermitted() {
startAgent();
final Peer peer = createPeer();
final MockPeerConnection connection = connection(peer);
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()), eq(peer), eq(Action.RLPX_ALLOW_NEW_INBOUND_CONNECTION));
connectionInitializer.simulateIncomingConnection(connection);
assertPeerConnectionNotTracked(peer);
assertThat(connection.getDisconnectReason()).contains(DisconnectReason.UNKNOWN);
}
@Test
public void connect_largeStreamOfPeers() {
final int maxPeers = 5;
final Stream<Peer> peerStream = Stream.generate(PeerTestHelper::createPeer).limit(20);
startAgentWithMaxPeers(maxPeers);
agent = spy(agent);
agent.connect(peerStream);
assertThat(agent.getConnectionCount()).isEqualTo(maxPeers);
// Check that stream was not fully iterated
verify(agent, times(maxPeers)).connect(any(Peer.class));
}
@Test
public void disconnect() throws ExecutionException, InterruptedException {
startAgent();
final Peer peer = spy(createPeer());
final CompletableFuture<PeerConnection> future = agent.connect(peer);
final MockPeerConnection connection = (MockPeerConnection) future.get();
// Sanity check connection was established
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(agent.getPeerConnection(peer)).isNotEmpty();
// Disconnect
final DisconnectReason reason = DisconnectReason.REQUESTED;
agent.disconnect(peer.getId(), reason);
// Validate peer was disconnected
assertThat(agent.getConnectionCount()).isEqualTo(0);
assertThat(connection.isDisconnected()).isTrue();
assertThat(connection.getDisconnectReason()).contains(reason);
assertPeerConnectionNotTracked(peer);
// Additional requests to disconnect should do nothing
agent.disconnect(peer.getId(), reason);
agent.disconnect(peer.getId(), reason);
assertThat(agent.getConnectionCount()).isEqualTo(0);
}
@Test
public void getConnectionCount() throws ExecutionException, InterruptedException {
startAgent();
final Peer peerA = createPeer();
final Peer peerB = createPeer();
final Peer peerC = createPeer();
assertThat(agent.getConnectionCount()).isEqualTo(0);
agent.connect(peerA);
assertThat(agent.getConnectionCount()).isEqualTo(1);
agent.connect(peerA);
assertThat(agent.getConnectionCount()).isEqualTo(1);
agent.connect(peerB);
assertThat(agent.getConnectionCount()).isEqualTo(2);
agent.connect(peerC);
assertThat(agent.getConnectionCount()).isEqualTo(3);
// Disconnect should decrement count
agent.disconnect(peerB.getId(), DisconnectReason.UNKNOWN);
assertThat(agent.getConnectionCount()).isEqualTo(2);
}
@Test
public void permissionsUpdate_permissionsRestrictedWithNoListOfPeers()
throws ExecutionException, InterruptedException {
final Peer permittedPeer = createPeer();
final Peer nonPermittedPeer = createPeer();
startAgent();
final PeerConnection permittedConnection = agent.connect(permittedPeer).get();
final PeerConnection nonPermittedConnection = agent.connect(nonPermittedPeer).get();
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()),
eq(nonPermittedPeer),
eq(Action.RLPX_ALLOW_ONGOING_LOCALLY_INITIATED_CONNECTION));
peerPermissions.testDispatchUpdate(true, Optional.empty());
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(agent.getPeerConnection(permittedPeer)).isNotEmpty();
assertPeerConnectionNotTracked(nonPermittedPeer);
assertThat(permittedConnection.isDisconnected()).isFalse();
assertThat(nonPermittedConnection.isDisconnected()).isTrue();
}
@Test
public void permissionsUpdate_permissionsRestrictedWithListOfPeers()
throws ExecutionException, InterruptedException {
final Peer permittedPeer = createPeer();
final Peer nonPermittedPeer = createPeer();
startAgent();
final PeerConnection permittedConnection = agent.connect(permittedPeer).get();
final PeerConnection nonPermittedConnection = agent.connect(nonPermittedPeer).get();
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()),
eq(nonPermittedPeer),
eq(Action.RLPX_ALLOW_ONGOING_LOCALLY_INITIATED_CONNECTION));
peerPermissions.testDispatchUpdate(true, Optional.of(Arrays.asList(nonPermittedPeer)));
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(agent.getPeerConnection(permittedPeer)).isNotEmpty();
assertPeerConnectionNotTracked(nonPermittedPeer);
assertThat(permittedConnection.isDisconnected()).isFalse();
assertThat(nonPermittedConnection.isDisconnected()).isTrue();
}
@Test
public void permissionsUpdate_permissionsRestrictedForRemotelyInitiatedConnections()
throws ExecutionException, InterruptedException {
final Peer locallyConnectedPeer = createPeer();
final Peer remotelyConnectedPeer = createPeer();
startAgent();
final PeerConnection locallyInitiatedConnection = agent.connect(locallyConnectedPeer).get();
final PeerConnection remotelyInitiatedConnection = connection(remotelyConnectedPeer);
connectionInitializer.simulateIncomingConnection(remotelyInitiatedConnection);
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()),
any(),
eq(Action.RLPX_ALLOW_ONGOING_REMOTELY_INITIATED_CONNECTION));
peerPermissions.testDispatchUpdate(true, Optional.empty());
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertThat(agent.getPeerConnection(locallyConnectedPeer)).isNotEmpty();
assertPeerConnectionNotTracked(remotelyConnectedPeer);
assertThat(locallyInitiatedConnection.isDisconnected()).isFalse();
assertThat(remotelyInitiatedConnection.isDisconnected()).isTrue();
}
@Test
public void permissionsUpdate_permissionsRestrictedForLocallyInitiatedConnections()
throws ExecutionException, InterruptedException {
final Peer locallyConnectedPeer = createPeer();
final Peer remotelyConnectedPeer = createPeer();
startAgent();
final PeerConnection locallyInitiatedConnection = agent.connect(locallyConnectedPeer).get();
final PeerConnection remotelyInitiatedConnection = connection(remotelyConnectedPeer);
connectionInitializer.simulateIncomingConnection(remotelyInitiatedConnection);
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
doReturn(false)
.when(peerPermissions)
.isPermitted(
eq(localNode.getPeer()),
any(),
eq(Action.RLPX_ALLOW_ONGOING_LOCALLY_INITIATED_CONNECTION));
peerPermissions.testDispatchUpdate(true, Optional.empty());
assertThat(agent.getConnectionCount()).isEqualTo(1);
assertPeerConnectionNotTracked(locallyConnectedPeer);
assertThat(agent.getPeerConnection(remotelyConnectedPeer)).isNotEmpty();
assertThat(locallyInitiatedConnection.isDisconnected()).isTrue();
assertThat(remotelyInitiatedConnection.isDisconnected()).isFalse();
}
@Test
public void permissionsUpdate_permissionsRelaxedWithNoListOfPeers()
throws ExecutionException, InterruptedException {
final Peer peerA = createPeer();
final Peer peerB = createPeer();
startAgent();
final PeerConnection connectionA = agent.connect(peerA).get();
final PeerConnection connectionB = agent.connect(peerB).get();
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
peerPermissions.testDispatchUpdate(false, Optional.empty());
assertThat(agent.getConnectionCount()).isEqualTo(2);
assertThat(agent.getPeerConnection(peerA)).isNotEmpty();
assertThat(agent.getPeerConnection(peerB)).isNotEmpty();
assertThat(connectionA.isDisconnected()).isFalse();
assertThat(connectionB.isDisconnected()).isFalse();
}
@Test
public void permissionsUpdate_permissionsRelaxedWithListOfPeers()
throws ExecutionException, InterruptedException {
final Peer peerA = createPeer();
final Peer peerB = createPeer();
startAgent();
final PeerConnection connectionA = agent.connect(peerA).get();
final PeerConnection connectionB = agent.connect(peerB).get();
// Sanity check
assertThat(agent.getConnectionCount()).isEqualTo(2);
peerPermissions.testDispatchUpdate(false, Optional.of(Arrays.asList(peerA)));
assertThat(agent.getConnectionCount()).isEqualTo(2);
assertThat(agent.getPeerConnection(peerA)).isNotEmpty();
assertThat(agent.getPeerConnection(peerB)).isNotEmpty();
assertThat(connectionA.isDisconnected()).isFalse();
assertThat(connectionB.isDisconnected()).isFalse();
}
@Test
public void subscribeConnect_firesForOutgoingConnection() {
final Peer peer = createPeer();
startAgent();
final AtomicReference<PeerConnection> connection = new AtomicReference<>();
agent.subscribeConnect(connection::set);
agent.connect(peer);
assertThat(connection.get()).isNotNull();
assertThat(connection.get().getPeer()).isEqualTo(peer);
}
@Test
public void subscribeConnect_firesForIncomingConnection() {
final Peer peer = createPeer();
startAgent();
final AtomicReference<PeerConnection> connection = new AtomicReference<>();
agent.subscribeConnect(connection::set);
connectionInitializer.simulateIncomingConnection(connection(peer));
assertThat(connection.get()).isNotNull();
assertThat(connection.get().getPeer()).isEqualTo(peer);
}
@Test
public void subscribeDisconnect() {
final Peer peer = createPeer();
startAgent();
final AtomicReference<PeerConnection> connection = new AtomicReference<>();
agent.subscribeDisconnect((conn, reason, initiatedByPeer) -> connection.set(conn));
agent.connect(peer);
agent.disconnect(peer.getId(), DisconnectReason.REQUESTED);
assertThat(connection.get()).isNotNull();
assertThat(connection.get().getPeer()).isEqualTo(peer);
}
@Test
public void subscribeMessage() throws ExecutionException, InterruptedException, PeerNotConnected {
final Peer peer = createPeer();
final Capability cap = Capability.create("eth", 63);
startAgent();
final AtomicBoolean eventFired = new AtomicBoolean(false);
agent.subscribeMessage(cap, (capability, msg) -> eventFired.set(true));
final PeerConnection connection = agent.connect(peer).get();
peerConnectionEvents.dispatchMessage(
Capability.create("eth", 63), connection, PingMessage.get());
assertThat(eventFired).isTrue();
}
@Test
public void getPeerConnection_pending() {
connectionInitializer.setAutocompleteConnections(false);
startAgent();
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = agent.connect(peer);
assertThat(future).isNotDone();
assertThat(agent.getPeerConnection(peer)).contains(future);
}
@Test
public void getPeerConnection_established() {
startAgent();
final Peer peer = createPeer();
final CompletableFuture<PeerConnection> future = agent.connect(peer);
assertThat(future).isDone();
assertThat(agent.getPeerConnection(peer)).contains(future);
}
private void assertPeerConnectionNotTracked(final Peer peer) {
assertThat(agent.getPeerConnection(peer)).isEmpty();
assertThat(agent.connectionsById.get(peer.getId())).isNull();
}
private void startAgent() {
startAgent(Peer.randomId());
}
private void startAgentWithMaxPeers(final int maxPeers) {
config.setMaxPeers(maxPeers);
agent = agent();
startAgent();
}
private void startAgent(final BytesValue nodeId) {
agent.start();
localNode.setEnode(enodeBuilder().nodeId(nodeId).build());
}
private RlpxAgent agent() {
return RlpxAgent.builder()
.keyPair(KEY_PAIR)
.config(config)
.peerPermissions(peerPermissions)
.peerProperties(peerProperties)
.localNode(localNode)
.metricsSystem(metrics)
.connectionInitializer(connectionInitializer)
.connectionEvents(peerConnectionEvents)
.build();
}
private MockPeerConnection connection(final Peer peer) {
return MockPeerConnection.create(peer, peerConnectionEvents);
}
private static class TestPeerPermissions extends PeerPermissions {
@Override
public boolean isPermitted(final Peer localNode, final Peer remotePeer, final Action action) {
return true;
}
public void testDispatchUpdate(
final boolean permissionsRestricted, final Optional<List<Peer>> affectedPeers) {
this.dispatchUpdate(permissionsRestricted, affectedPeers);
}
}
}
|
/*
* BSD 3-Clause License
*
* Copyright (c) 2021, Joint Research Centre (JRC) 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.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package eu.cise.sim.dropw.context;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.bundles.assets.AssetsBundleConfiguration;
import io.dropwizard.bundles.assets.AssetsConfiguration;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/**
* CiseSimDropwizardConf
* general purpose class
* extending Configuration (dropwizard)
*/
public class SimConf extends Configuration implements AssetsBundleConfiguration {
@Valid
@NotNull
@JsonProperty
private final AssetsConfiguration assets = AssetsConfiguration.builder().build();
@Override
public AssetsConfiguration getAssetsConfiguration() {
return assets;
}
}
|
/*
* 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 edu.internet2.middleware.tierApiAuthzClientExt.org.apache.commons.lang.text;
import java.util.Arrays;
/**
* A matcher class that can be queried to determine if a character array
* portion matches.
* <p>
* This class comes complete with various factory methods.
* If these do not suffice, you can subclass and implement your own matcher.
*
* @author Apache Software Foundation
* @since 2.2
* @version $Id: StrMatcher.java 905636 2010-02-02 14:03:32Z niallp $
*/
public abstract class StrMatcher {
/**
* Matches the comma character.
*/
private static final StrMatcher COMMA_MATCHER = new CharMatcher(',');
/**
* Matches the tab character.
*/
private static final StrMatcher TAB_MATCHER = new CharMatcher('\t');
/**
* Matches the space character.
*/
private static final StrMatcher SPACE_MATCHER = new CharMatcher(' ');
/**
* Matches the same characters as StringTokenizer,
* namely space, tab, newline, formfeed.
*/
private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray());
/**
* Matches the String trim() whitespace characters.
*/
private static final StrMatcher TRIM_MATCHER = new TrimMatcher();
/**
* Matches the double quote character.
*/
private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\'');
/**
* Matches the double quote character.
*/
private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"');
/**
* Matches the single or double quote character.
*/
private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray());
/**
* Matches no characters.
*/
private static final StrMatcher NONE_MATCHER = new NoMatcher();
// -----------------------------------------------------------------------
/**
* Returns a matcher which matches the comma character.
*
* @return a matcher for a comma
*/
public static StrMatcher commaMatcher() {
return COMMA_MATCHER;
}
/**
* Returns a matcher which matches the tab character.
*
* @return a matcher for a tab
*/
public static StrMatcher tabMatcher() {
return TAB_MATCHER;
}
/**
* Returns a matcher which matches the space character.
*
* @return a matcher for a space
*/
public static StrMatcher spaceMatcher() {
return SPACE_MATCHER;
}
/**
* Matches the same characters as StringTokenizer,
* namely space, tab, newline and formfeed.
*
* @return the split matcher
*/
public static StrMatcher splitMatcher() {
return SPLIT_MATCHER;
}
/**
* Matches the String trim() whitespace characters.
*
* @return the trim matcher
*/
public static StrMatcher trimMatcher() {
return TRIM_MATCHER;
}
/**
* Returns a matcher which matches the single quote character.
*
* @return a matcher for a single quote
*/
public static StrMatcher singleQuoteMatcher() {
return SINGLE_QUOTE_MATCHER;
}
/**
* Returns a matcher which matches the double quote character.
*
* @return a matcher for a double quote
*/
public static StrMatcher doubleQuoteMatcher() {
return DOUBLE_QUOTE_MATCHER;
}
/**
* Returns a matcher which matches the single or double quote character.
*
* @return a matcher for a single or double quote
*/
public static StrMatcher quoteMatcher() {
return QUOTE_MATCHER;
}
/**
* Matches no characters.
*
* @return a matcher that matches nothing
*/
public static StrMatcher noneMatcher() {
return NONE_MATCHER;
}
/**
* Constructor that creates a matcher from a character.
*
* @param ch the character to match, must not be null
* @return a new Matcher for the given char
*/
public static StrMatcher charMatcher(char ch) {
return new CharMatcher(ch);
}
/**
* Constructor that creates a matcher from a set of characters.
*
* @param chars the characters to match, null or empty matches nothing
* @return a new matcher for the given char[]
*/
public static StrMatcher charSetMatcher(char[] chars) {
if (chars == null || chars.length == 0) {
return NONE_MATCHER;
}
if (chars.length == 1) {
return new CharMatcher(chars[0]);
}
return new CharSetMatcher(chars);
}
/**
* Constructor that creates a matcher from a string representing a set of characters.
*
* @param chars the characters to match, null or empty matches nothing
* @return a new Matcher for the given characters
*/
public static StrMatcher charSetMatcher(String chars) {
if (chars == null || chars.length() == 0) {
return NONE_MATCHER;
}
if (chars.length() == 1) {
return new CharMatcher(chars.charAt(0));
}
return new CharSetMatcher(chars.toCharArray());
}
/**
* Constructor that creates a matcher from a string.
*
* @param str the string to match, null or empty matches nothing
* @return a new Matcher for the given String
*/
public static StrMatcher stringMatcher(String str) {
if (str == null || str.length() == 0) {
return NONE_MATCHER;
}
return new StringMatcher(str);
}
//-----------------------------------------------------------------------
/**
* Constructor.
*/
protected StrMatcher() {
super();
}
/**
* Returns the number of matching characters, zero for no match.
* <p>
* This method is called to check for a match.
* The parameter <code>pos</code> represents the current position to be
* checked in the string <code>buffer</code> (a character array which must
* not be changed).
* The API guarantees that <code>pos</code> is a valid index for <code>buffer</code>.
* <p>
* The character array may be larger than the active area to be matched.
* Only values in the buffer between the specifed indices may be accessed.
* <p>
* The matching code may check one character or many.
* It may check characters preceeding <code>pos</code> as well as those
* after, so long as no checks exceed the bounds specified.
* <p>
* It must return zero for no match, or a positive number if a match was found.
* The number indicates the number of characters that matched.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
/**
* Returns the number of matching characters, zero for no match.
* <p>
* This method is called to check for a match.
* The parameter <code>pos</code> represents the current position to be
* checked in the string <code>buffer</code> (a character array which must
* not be changed).
* The API guarantees that <code>pos</code> is a valid index for <code>buffer</code>.
* <p>
* The matching code may check one character or many.
* It may check characters preceeding <code>pos</code> as well as those after.
* <p>
* It must return zero for no match, or a positive number if a match was found.
* The number indicates the number of characters that matched.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @return the number of matching characters, zero for no match
* @since 2.4
*/
public int isMatch(char[] buffer, int pos) {
return isMatch(buffer, pos, 0, buffer.length);
}
//-----------------------------------------------------------------------
/**
* Class used to define a set of characters for matching purposes.
*/
static final class CharSetMatcher extends StrMatcher {
/** The set of characters to match. */
private final char[] chars;
/**
* Constructor that creates a matcher from a character array.
*
* @param chars the characters to match, must not be null
*/
CharSetMatcher(char chars[]) {
super();
this.chars = (char[]) chars.clone();
Arrays.sort(this.chars);
}
/**
* Returns whether or not the given character matches.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
}
}
//-----------------------------------------------------------------------
/**
* Class used to define a character for matching purposes.
*/
static final class CharMatcher extends StrMatcher {
/** The character to match. */
private final char ch;
/**
* Constructor that creates a matcher that matches a single character.
*
* @param ch the character to match
*/
CharMatcher(char ch) {
super();
this.ch = ch;
}
/**
* Returns whether or not the given character matches.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
return ch == buffer[pos] ? 1 : 0;
}
}
//-----------------------------------------------------------------------
/**
* Class used to define a set of characters for matching purposes.
*/
static final class StringMatcher extends StrMatcher {
/** The string to match, as a character array. */
private final char[] chars;
/**
* Constructor that creates a matcher from a String.
*
* @param str the string to match, must not be null
*/
StringMatcher(String str) {
super();
chars = str.toCharArray();
}
/**
* Returns whether or not the given text matches the stored string.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
int len = chars.length;
if (pos + len > bufferEnd) {
return 0;
}
for (int i = 0; i < chars.length; i++, pos++) {
if (chars[i] != buffer[pos]) {
return 0;
}
}
return len;
}
}
//-----------------------------------------------------------------------
/**
* Class used to match no characters.
*/
static final class NoMatcher extends StrMatcher {
/**
* Constructs a new instance of <code>NoMatcher</code>.
*/
NoMatcher() {
super();
}
/**
* Always returns <code>false</code>.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
return 0;
}
}
//-----------------------------------------------------------------------
/**
* Class used to match whitespace as per trim().
*/
static final class TrimMatcher extends StrMatcher {
/**
* Constructs a new instance of <code>TrimMatcher</code>.
*/
TrimMatcher() {
super();
}
/**
* Returns whether or not the given character matches.
*
* @param buffer the text content to match against, do not change
* @param pos the starting position for the match, valid for buffer
* @param bufferStart the first active index in the buffer, valid for buffer
* @param bufferEnd the end index of the active buffer, valid for buffer
* @return the number of matching characters, zero for no match
*/
public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) {
return buffer[pos] <= 32 ? 1 : 0;
}
}
}
|
package diy.uigeneric.data;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import diy.restlite.HttpRestLite;
import static junit.framework.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class SampleServerIndirectListTest {
private static final String TAG = SampleServerIndirectListTest.class.getSimpleName();
@Before
public void before() {
Context context = InstrumentationRegistry.getTargetContext();
SampleServerIndirectList list = new SampleServerIndirectList(context);
list.removeAll();
}
@Test
public void test() {
Context context = InstrumentationRegistry.getTargetContext();
SampleServerIndirectList list = new SampleServerIndirectList(context);
SampleServerDataSource source = new SampleServerDataSource(context);
SampleServerDataSource.SampleHolder holder = new SampleServerDataSource.SampleHolder();
Sample sample;
HttpRestLite.Result result;
// tests add
sample = new Sample();
sample.setName("Aaa");
result = source.add(sample, holder);
Log.d(TAG, "result.errorCode == " + result.errorCode);
assertTrue(result.errorCode == 0);
assertTrue(holder.sample.getName().equals("Aaa"));
sample = new Sample();
sample.setName("Bbb");
result = source.add(sample, holder);
Log.d(TAG, "result.errorCode == " + result.errorCode);
assertTrue(result.errorCode == 0);
assertTrue(holder.sample.getName().equals("Bbb"));
sample = new Sample();
sample.setName("Ccc");
result = source.add(sample, holder);
Log.d(TAG, "result.errorCode == " + result.errorCode);
assertTrue(result.errorCode == 0);
assertTrue(holder.sample.getName().equals("Ccc"));
// tests list
result = list.load(null, null, null, SampleServerIndirectList.SORT_NAME_NATURAL, true);
Log.d(TAG, "result.errorCode == " + result.errorCode);
assertTrue(result.errorCode == 0);
assertTrue(list.get(0).getName().equals("Ccc"));
assertTrue(list.get(1).getName().equals("Bbb"));
assertTrue(list.get(2).getName().equals("Aaa"));
assertTrue(list.size() == 3);
}
}
|
package com.haozi.id.generator.core.util;
import lombok.extern.slf4j.Slf4j;
import java.net.NetworkInterface;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Enumeration;
/**
* Snowflake算法
*
* @author haozi
* @date 2019-12-1819:14
*/
@Slf4j
public class Snowflake {
private static final int TOTAL_BITS = 64;
private static final int EPOCH_BITS = 42;
private static final int NODE_ID_BITS = 10;
private static final int SEQUENCE_BITS = 12;
private static final int maxNodeId = (int) (Math.pow(2, NODE_ID_BITS) - 1);
private static final int maxSequence = (int) (Math.pow(2, SEQUENCE_BITS) - 1);
// Custom Epoch (January 1, 2015 Midnight UTC = 2015-01-01T00:00:00Z)
private static final long CUSTOM_EPOCH = 1420070400000L;
private static final int nodeId = createNodeId();
private static volatile long lastTimestamp = -1L;
private static volatile long sequence = 0L;
public synchronized static long nextId() {
long currentTimestamp = timestamp();
if (currentTimestamp < lastTimestamp) {
throw new IllegalStateException("Invalid System Clock!");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0) {
// Sequence Exhausted, wait till next millisecond.
currentTimestamp = waitNextMillis(currentTimestamp);
}
} else {
// reset sequence to start with zero for the next millisecond
sequence = 0;
}
lastTimestamp = currentTimestamp;
long id = currentTimestamp << (TOTAL_BITS - EPOCH_BITS);
id |= (nodeId << (TOTAL_BITS - EPOCH_BITS - NODE_ID_BITS));
id |= sequence;
return id;
}
// Get current timestamp in milliseconds, adjust for the custom epoch.
private static long timestamp() {
return Instant.now().toEpochMilli() - CUSTOM_EPOCH;
}
// Block and wait till next millisecond
private static long waitNextMillis(long currentTimestamp) {
while (currentTimestamp == lastTimestamp) {
currentTimestamp = timestamp();
}
return currentTimestamp;
}
private static int createNodeId() {
int nodeId;
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X", mac[i]));
}
}
}
nodeId = sb.toString().hashCode();
} catch (Exception ex) {
nodeId = (new SecureRandom().nextInt());
}
nodeId = nodeId & maxNodeId;
log.info("nodeId is {}", nodeId);
return nodeId;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.