All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.vertx.lang.groovy.InternalHelper.groovy Maven / Gradle / Ivy

There is a newer version: 5.0.0.CR3
Show newest version
/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Red Hat 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 io.vertx.lang.groovy;

import groovy.transform.CompileStatic;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.groovy.core.buffer.Buffer

import java.lang.reflect.Constructor;

/**
 * @author Julien Viet
 */
@CompileStatic
public class InternalHelper {

  public static Object unwrapObject(Object obj) {
    if (obj instanceof Map) {
      return new JsonObject((Map) obj);
    } else if (obj instanceof List) {
      return new JsonArray((List) obj);
    } else if (obj instanceof Buffer) {
      return ((Buffer) obj).getDelegate();
    } else if (obj instanceof GString) {
      return ((GString) obj).toString();
    }
    return obj;
  }

  public static Object wrapObject(Object obj) {
    if (obj instanceof JsonObject) {
      return ((JsonObject) obj).getMap().collectEntries { k, v ->
        [k, wrapObject(v)]
      }
    } else if (obj instanceof JsonArray) {
      return ((JsonArray) obj).toList().collect {
        wrapObject(it)
      }
    } else if (obj instanceof io.vertx.core.buffer.Buffer) {
      return new Buffer((io.vertx.core.buffer.Buffer) obj);
    }
    return obj;
  }

  public static  AsyncResult result(V value) {
    return Future.succeededFuture(value);
  }

  public static  AsyncResult failure(Throwable t) {
    return Future.failedFuture(t);
  }

  public static  T safeCreate(D delegate, Class type) {
    if (delegate != null) {
      Constructor ctor = type.getConstructor(Object.class)
      return ctor.newInstance(delegate)
    }
    return null
  }

}