| /** |
| ******************************************************************************** |
| * Copyright (c) 2020 Robert Bosch GmbH and others. |
| * |
| * This program and the accompanying materials are made |
| * available under the terms of the Eclipse Public License 2.0 |
| * which is available at https://www.eclipse.org/legal/epl-2.0/ |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| * |
| * Contributors: |
| * Robert Bosch GmbH - initial API and implementation |
| ******************************************************************************** |
| */ |
| |
| package org.eclipse.app4mc.amalthea.model; |
| |
| import static com.google.common.base.Preconditions.checkArgument; |
| |
| import java.io.UnsupportedEncodingException; |
| import java.net.URLEncoder; |
| import java.nio.charset.StandardCharsets; |
| |
| import org.eclipse.emf.common.util.EList; |
| import org.eclipse.jdt.annotation.NonNull; |
| import org.eclipse.jdt.annotation.Nullable; |
| |
| /** |
| * This class provides static helper methods (extension methods). |
| * <p> |
| * The methods are called from several generated model objects. |
| */ |
| public class AmaltheaExtensions { |
| |
| // Suppress default constructor |
| private AmaltheaExtensions() { |
| throw new IllegalStateException("Utility class"); |
| } |
| |
| private static final String ARG_STRING_MESSAGE = "Argument is null, expected: String"; |
| private static final String ARG_LIST_MESSAGE = "Argument is null, expected: EList"; |
| private static final String ARG_LIST_ITEM_MESSAGE = "List argument contains null"; |
| |
| public static String toPlainString(final @NonNull EList<@NonNull String> segments, final @NonNull String delimiter) { |
| checkArgument(segments != null, ARG_LIST_MESSAGE); |
| checkArgument(!segments.contains(null), ARG_LIST_ITEM_MESSAGE); |
| checkArgument(delimiter != null, ARG_STRING_MESSAGE); |
| |
| if (segments.isEmpty()) return ""; |
| |
| StringBuilder result = new StringBuilder(segments.get(0)); |
| for (int i = 1; i < segments.size(); i++) { |
| result.append(delimiter); |
| result.append(segments.get(i)); |
| } |
| return result.toString(); |
| } |
| |
| public static String toEncodedString(final @NonNull EList<@NonNull String> segments) { |
| checkArgument(segments != null, ARG_LIST_MESSAGE); |
| checkArgument(!segments.contains(null), ARG_LIST_ITEM_MESSAGE); |
| |
| if (segments.isEmpty()) return ""; |
| |
| StringBuilder result = new StringBuilder(encode(segments.get(0))); |
| for (int i = 1; i < segments.size(); i++) { |
| result.append("/"); |
| result.append(encode(segments.get(i))); |
| } |
| return result.toString(); |
| } |
| |
| public static String encode(final @Nullable String str) { |
| if (str == null || str.isEmpty()) return "no-name"; |
| |
| try { |
| return URLEncoder.encode(str, StandardCharsets.UTF_8.toString()); |
| } catch (UnsupportedEncodingException e) { |
| throw org.eclipse.xtext.xbase.lib.Exceptions.sneakyThrow(e); |
| } |
| } |
| } |