com.teamscale.commons.service.client.ISerializationFormat Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-commons Show documentation
Show all versions of teamscale-commons Show documentation
Provides common DTOs for Teamscale
The newest version!
/*
* Copyright (c) CQSE GmbH
*
* 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.teamscale.commons.service.client;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import com.teamscale.commons.service.EMimeType;
/**
* Provides a serialization strategy for service calls.
*/
public interface ISerializationFormat {
/**
* Returns the MIME type that should be sent to the server as "Content-Type" header. May return
* empty to indicate that the Content-Type header should not be set.
*/
Optional getMimeType();
/** Returns the serialized data. */
String serialize(T data);
/** Serializes the given data and wraps it into an HttpEntity. */
default HttpEntity toHttpEntity(T data) {
return new StringEntity(serialize(data), StandardCharsets.UTF_8);
}
/**
* Constructs a serializer, which expects a List and sends them as url encoded form
* data.
*/
static ISerializationFormat> toUrlEncodedFormData() {
return new ISerializationFormat<>() {
@Override
public Optional getMimeType() {
return Optional.of(EMimeType.URL_ENCODED_FORM_DATA);
}
@Override
public String serialize(List data) {
return URLEncodedUtils.format(data, StandardCharsets.UTF_8);
}
};
}
/**
* Constructs a serializer, which expects a raw HttpEntity that should be sent as multipart form
* data.
*/
static ISerializationFormat toMultiPart() {
return new ISerializationFormat<>() {
@Override
public Optional getMimeType() {
return Optional.empty();
}
@Override
public String serialize(HttpEntity data) {
throw new IllegalStateException("This should never be called directly. Call via toHttpEntity().");
}
@Override
public HttpEntity toHttpEntity(HttpEntity data) {
return data;
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy