text:
.class public Lcom/facebook/internal/AttributionIdentifiers;
.super Ljava/lang/Object;
.source ""

# static fields
.field private static final ANDROID_ID_COLUMN_NAME:Ljava/lang/String; = "androidid"

.field private static final ATTRIBUTION_ID_COLUMN_NAME:Ljava/lang/String; = "aid"

.field private static final ATTRIBUTION_ID_CONTENT_URI:Landroid/net/Uri; = null

.field private static final CONNECTION_RESULT_SUCCESS:I = 0x0

.field private static final IDENTIFIER_REFRESH_INTERVAL_MILLIS:J = 0x36ee80L

.field private static final LIMIT_TRACKING_COLUMN_NAME:Ljava/lang/String; = "limit_tracking"

.field private static final TAG:Ljava/lang/String; = null

.field private static recentlyFetchedIdentifiers:Lcom/facebook/internal/AttributionIdentifiers; = null

# instance fields
.field private androidAdvertiserId:Ljava/lang/String;

.field private attributionId:Ljava/lang/String;

.field private fetchTime:J

.field private limitTracking:Z

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .line 32
    const-class v0, Lcom/facebook/internal/AttributionIdentifiers;

    invoke-virtual {v0}, Ljava/lang/Class;->getCanonicalName()Ljava/lang/String;

    move-result-object v0

    sput-object v0, Lcom/facebook/internal/AttributionIdentifiers;->TAG:Ljava/lang/String;

    .line 33
    const-string v0, "content://com.facebook.katana.provider.AttributionIdProvider"

    invoke-static {v0}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    sput-object v0, Lcom/facebook/internal/AttributionIdentifiers;->ATTRIBUTION_ID_CONTENT_URI:Landroid/net/Uri;

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    .line 31
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method private static getAndroidId(Landroid/content/Context;)Lcom/facebook/internal/AttributionIdentifiers;
    .locals 8

    .line 52
    new-instance v5, Lcom/facebook/internal/AttributionIdentifiers;

    invoke-direct {v5}, Lcom/facebook/internal/AttributionIdentifiers;-><init>()V

    .line 54
    :try_start_0
    const-string v0, "com.google.android.gms.common.GooglePlayServicesUtil"

    const-string v1, "isGooglePlayServicesAvailable"

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Class;

    const-class v3, Landroid/content/Context;

    const/4 v4, 0x0

    aput-object v3, v2, v4

    invoke-static {v0, v1, v2}, Lcom/facebook/internal/Utility;->getMethodQuietly(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v0

    .line 60
    move-object v6, v0

    if-nez v0, :cond_0
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    .line 61
    return-object v5

    .line 64
    :cond_0
    :try_start_1
    const/4 v0, 0x1

    new-array v0, v0, [Ljava/lang/Object;

    const/4 v1, 0x0

    aput-object p0, v0, v1

    const/4 v1, 0x0

    invoke-static {v1, v6, v0}, Lcom/facebook/internal/Utility;->invokeMethodQuietly(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    .line 65
    move-object v6, v0

    instance-of v0, v0, Ljava/lang/Integer;

    if-eqz v0, :cond_1

    move-object v0, v6

    check-cast v0, Ljava/lang/Integer;

    invoke-virtual {v0}, Ljava/lang/Integer;->intValue()I

    move-result v0

    if-eqz v0, :cond_2
    :try_end_1
    .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0

    .line 66
    :cond_1
    return-object v5

    .line 69
    :cond_2
    :try_start_2
    const-string v0, "com.google.android.gms.ads.identifier.AdvertisingIdClient"

    const-string v1, "getAdvertisingIdInfo"

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Class;

    const-class v3, Landroid/content/Context;

    const/4 v4, 0x0

    aput-object v3, v2, v4

    invoke-static {v0, v1, v2}, Lcom/facebook/internal/Utility;->getMethodQuietly(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v0

    .line 74
    move-object v6, v0

    if-nez v0, :cond_3
    :try_end_2
    .catch Ljava/lang/Exception; {:try_start_2 .. :try_end_2} :catch_0

    .line 75
    return-object v5

    .line 77
    :cond_3
    :try_start_3
    const/4 v0, 0x1

    new-array v0, v0, [Ljava/lang/Object;

    const/4 v1, 0x0

    aput-object p0, v0, v1

    const/4 v1, 0x0

    invoke-static {v1, v6, v0}, Lcom/facebook/internal/Utility;->invokeMethodQuietly(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    .line 78
    move-object p0, v0

    if-nez v0, :cond_4
    :try_end_3
    .catch Ljava/lang/Exception; {:try_start_3 .. :try_end_3} :catch_0

    .line 79
    return-object v5

    .line 82
    :cond_4
    :try_start_4
    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v0

    const-string v1, "getId"

    const/4 v2, 0x0

    new-array v2, v2, [Ljava/lang/Class;

    invoke-static {v0, v1, v2}, Lcom/facebook/internal/Utility;->getMethodQuietly(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v6

    .line 83
    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v0

    const-string v1, "isLimitAdTrackingEnabled"

    const/4 v2, 0x0

    new-array v2, v2, [Ljava/lang/Class;

    invoke-static {v0, v1, v2}, Lcom/facebook/internal/Utility;->getMethodQuietly(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;

    move-result-object v7

    .line 84
    if-eqz v6, :cond_5

    if-nez v7, :cond_6
    :try_end_4
    .catch Ljava/lang/Exception; {:try_start_4 .. :try_end_4} :catch_0

    .line 85
    :cond_5
    return-object v5

    .line 88
    :cond_6
    :try_start_5
    const/4 v0, 0x0

    new-array v0, v0, [Ljava/lang/Object;

    invoke-static {p0, v6, v0}, Lcom/facebook/internal/Utility;->invokeMethodQuietly(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    iput-object v0, v5, Lcom/facebook/internal/AttributionIdentifiers;->androidAdvertiserId:Ljava/lang/String;

    .line 89
    const/4 v0, 0x0

    new-array v0, v0, [Ljava/lang/Object;

    invoke-static {p0, v7, v0}, Lcom/facebook/internal/Utility;->invokeMethodQuietly(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Boolean;

    invoke-virtual {v0}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0

    iput-boolean v0, v5, Lcom/facebook/internal/AttributionIdentifiers;->limitTracking:Z
    :try_end_5
    .catch Ljava/lang/Exception; {:try_start_5 .. :try_end_5} :catch_0

    .line 92
    goto :goto_0

    .line 90
    :catch_0
    move-exception v6

    .line 91
    const-string v0, "android_id"

    invoke-static {v0, v6}, Lcom/facebook/internal/Utility;->logd(Ljava/lang/String;Ljava/lang/Exception;)V

    .line 93
    :goto_0
    return-object v5
.end method

.method public static getAttributionIdentifiers(Landroid/content/Context;)Lcom/facebook/internal/AttributionIdentifiers;
    .locals 10

    .line 97
    sget-object v0, Lcom/facebook/internal/AttributionIdentifiers;->recentlyFetchedIdentifiers:Lcom/facebook/internal/AttributionIdentifiers;

    if-eqz v0, :cond_0

    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v0

    sget-object v2, Lcom/facebook/internal/AttributionIdentifiers;->recentlyFetchedIdentifiers:Lcom/facebook/internal/AttributionIdentifiers;

    iget-wide v2, v2, Lcom/facebook/internal/AttributionIdentifiers;->fetchTime:J

    sub-long/2addr v0, v2

    const-wide/32 v2, 0x36ee80

    cmp-long v0, v0, v2

    if-gez v0, :cond_0

    .line 99
    sget-object v0, Lcom/facebook/internal/AttributionIdentifiers;->recentlyFetchedIdentifiers:Lcom/facebook/internal/AttributionIdentifiers;

    return-object v0

    .line 102
    :cond_0
    invoke-static {p0}, Lcom/facebook/internal/AttributionIdentifiers;->getAndroidId(Landroid/content/Context;)Lcom/facebook/internal/AttributionIdentifiers;

    move-result-object v6

    .line 105
    :try_start_0
    const/4 v0, 0x3

    new-array v7, v0, [Ljava/lang/String;

    const-string v0, "aid"

    const/4 v1, 0x0

    aput-object v0, v7, v1

    const-string v0, "androidid"

    const/4 v1, 0x1

    aput-object v0, v7, v1

    const-string v0, "limit_tracking"

    const/4 v1, 0x2

    aput-object v0, v7, v1

    .line 106
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    sget-object v1, Lcom/facebook/internal/AttributionIdentifiers;->ATTRIBUTION_ID_CONTENT_URI:Landroid/net/Uri;

    move-object v2, v7

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v0

    .line 107
    move-object p0, v0

    if-eqz v0, :cond_1

    invoke-interface {p0}, Landroid/database/Cursor;->moveToFirst()Z

    move-result v0

    if-nez v0, :cond_2
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    .line 108
    :cond_1
    const/4 v0, 0x0

    return-object v0

    .line 110
    :cond_2
    :try_start_1
    const-string v0, "aid"

    invoke-interface {p0, v0}, Landroid/database/Cursor;->getColumnIndex(Ljava/lang/String;)I

    move-result v7

    .line 111
    const-string v0, "androidid"

    invoke-interface {p0, v0}, Landroid/database/Cursor;->getColumnIndex(Ljava/lang/String;)I

    move-result v8

    .line 112
    const-string v0, "limit_tracking"

    invoke-interface {p0, v0}, Landroid/database/Cursor;->getColumnIndex(Ljava/lang/String;)I

    move-result v9

    .line 114
    invoke-interface {p0, v7}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    iput-object v0, v6, Lcom/facebook/internal/AttributionIdentifiers;->attributionId:Ljava/lang/String;

    .line 118
    if-lez v8, :cond_3

    if-lez v9, :cond_3

    invoke-virtual {v6}, Lcom/facebook/internal/AttributionIdentifiers;->getAndroidAdvertiserId()Ljava/lang/String;

    move-result-object v0

    if-nez v0, :cond_3

    .line 119
    invoke-interface {p0, v8}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    iput-object v0, v6, Lcom/facebook/internal/AttributionIdentifiers;->androidAdvertiserId:Ljava/lang/String;

    .line 120
    invoke-interface {p0, v9}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Ljava/lang/Boolean;->parseBoolean(Ljava/lang/String;)Z

    move-result v0

    iput-boolean v0, v6, Lcom/facebook/internal/AttributionIdentifiers;->limitTracking:Z

    .line 122
    :cond_3
    invoke-interface {p0}, Landroid/database/Cursor;->close()V
    :try_end_1
    .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0

    .line 126
    goto :goto_0

    .line 123
    .line 124
    :catch_0
    const/4 v0, 0x0

    return-object v0

    .line 128
    :goto_0
    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v0

    iput-wide v0, v6, Lcom/facebook/internal/AttributionIdentifiers;->fetchTime:J

    .line 129
    sput-object v6, Lcom/facebook/internal/AttributionIdentifiers;->recentlyFetchedIdentifiers:Lcom/facebook/internal/AttributionIdentifiers;

    .line 130
    return-object v6
.end method

# virtual methods
.method public getAndroidAdvertiserId()Ljava/lang/String;
    .locals 1

    .line 138
    iget-object v0, p0, Lcom/facebook/internal/AttributionIdentifiers;->androidAdvertiserId:Ljava/lang/String;

    return-object v0
.end method

.method public getAttributionId()Ljava/lang/String;
    .locals 1

    .line 134
    iget-object v0, p0, Lcom/facebook/internal/AttributionIdentifiers;->attributionId:Ljava/lang/String;

    return-object v0
.end method

.method public isTrackingLimited()Z
    .locals 1

    .line 142
    iget-boolean v0, p0, Lcom/facebook/internal/AttributionIdentifiers;->limitTracking:Z

    return v0
.end method


text:
'''
Created on 16.11.2011

@author: michi
'''
from PyQt4.QtCore import pyqtSlot, QDateTime
from PyQt4.QtNetwork import QNetworkReply, QNetworkRequest

from ems.qt4.location.maps.tiled.geotiledmapreply import GeoTiledMapReply

class GeoMapReplyNokia(GeoTiledMapReply):

    _m_reply = QNetworkReply

    def __init__(self, reply, request, parent=None):
        '''
        @param reply: QNetworkReply
        @type reply: QNetworkReply
        @param request: GeoTiledMapRequest
        @type request: GeoTiledMapRequest
        @param parent: Parent QObject
        @type parent: QObject
        '''
        GeoTiledMapReply.__init__(self, request, parent=parent)

        self._m_reply = reply
        self._m_reply.setParent(self)
        self._m_reply.finished.connect(self._networkFinished)
        self._m_reply.error.connect(self._networkError)
        self._m_reply.destroyed.connect(self._replyDestroyed)

    def networkReply(self):
        '''
        @rtype: QNetworkReply
        '''
        return self._m_reply

    def abort(self):
        if not self._m_reply:
            return
        self._m_reply.abort()

    @pyqtSlot()
    def _replyDestroyed(self):
        self._m_reply = None

    @pyqtSlot()
    def _networkFinished(self):
        if not self._m_reply:
            return

        if self._m_reply.error() != QNetworkReply.NoError:
            return

        fromCache = self._m_reply.attribute(QNetworkRequest.SourceIsFromCacheAttribute)
        self._setCached(fromCache.toBool())

        if not self.isChached():
            cache = self._m_reply.manager().cache()
            if cache:
                metaData = cache.metaData(self._m_reply.url())
                exp = QDateTime.currentDateTime()
                exp = exp.addDays(14)
                metaData.setExpirationDate(exp)
                cache.updateMetaData(metaData)

        self._setMapImageData(self._m_reply.readAll())
        self.setMapImageFormat("PNG")
        self._setFinished(True)

        self._m_reply.deleteLater()
        self._m_reply = None

    def _networkError(self, error):
        if not self._m_reply:
            return

        if error != QNetworkReply.OperationCanceledError:
            self._setError(GeoTiledMapReply.CommunicationError,
                           self._m_reply.errorString())
        self._setFinished(True)
        self._m_reply.deleteLater()
        self._m_reply = None

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace CodeCloud\ShopifyApiClient\EndpointFramework;

class ApiResponse
{
    /**
     * @var \stdClass
     */
    private $raw;

    /**
     * @var int
     */
    private $httpStatus;

    /**
     * @param \stdClass $rawResponse
     * @param int $httpStatus
     */
    public function __construct(\stdClass $rawResponse, $httpStatus)
    {
        $this->raw = $rawResponse;
        $this->httpStatus = $httpStatus;
    }

    /**
     * @param string $property
     * @param null|mixed $default
     * @return mixed
     */
    public function get($property, $default = null)
    {
        if (! property_exists($this->raw, $property)) {
            return $default;
        }

        return $this->raw->$property;
    }

    /**
     * @return bool
     */
    public function success()
    {
        return $this->httpStatus >= 200 && $this->httpStatus < 300;
    }

    /**
     * @param string $jsonString
     * @param integer $httpStatus
     * @return ApiResponse
     * @throws \Exception
     */
    public static function fromJson($jsonString, $httpStatus)
    {
        if (! $decoded = json_decode($jsonString)) {
            throw new \Exception('Could not JSON decode string: ' . $jsonString);
        }

        return new self($decoded, $httpStatus);
    }
}


text:
package com.restfiddle.controller.rest;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.restfiddle.constant.NodeType;
import com.restfiddle.dto.ConversationDTO;
import com.restfiddle.dto.FormDataDTO;
import com.restfiddle.dto.NodeDTO;
import com.restfiddle.dto.RfHeaderDTO;
import com.restfiddle.dto.RfRequestDTO;
import com.restfiddle.entity.BaseNode;
import com.restfiddle.entity.Conversation;

@RestController
@Transactional
public class FileUploadController {
    Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private NodeController nodeController;

    @Autowired
    private ConversationController conversationController;

    @RequestMapping(value = "/api/import", method = RequestMethod.POST)
    public @ResponseBody
    void upload(@RequestParam("projectId") String projectId, @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

	if (!file.isEmpty()) {
	    try {
		byte[] bytes = file.getBytes();
		String fileContent = new String(bytes);
		JSONObject pmCollection = new JSONObject(fileContent);

		String collectionName = pmCollection.getString("name");
		System.out.println(collectionName);
		//
		NodeDTO collectionNodeDTO = new NodeDTO();
		collectionNodeDTO.setName(collectionName);
		collectionNodeDTO.setNodeType(NodeType.FOLDER.name());
		collectionNodeDTO.setProjectId(projectId);
		BaseNode collectionNode = nodeController.create(projectId, collectionNodeDTO);

		JSONArray requests = pmCollection.getJSONArray("requests");
		int len = requests.length();
		for (int i = 0; i < len; i++) {
		    JSONObject request = (JSONObject) requests.get(i);
		    String requestName = request.getString("name");
		    String requestDescription = request.getString("description");
		    String requestUrl = request.getString("url");
		    String requestMethod = request.getString("method");

		    ConversationDTO conversationDTO = new ConversationDTO();
		    RfRequestDTO rfRequestDTO = new RfRequestDTO();
		    rfRequestDTO.setApiUrl(requestUrl);
		    rfRequestDTO.setMethodType(requestMethod);

		    String headersString = request.getString("headers");
		    if (headersString != null && !headersString.isEmpty()) {
			List<RfHeaderDTO> headerDTOs = new ArrayList<RfHeaderDTO>();
			RfHeaderDTO headerDTO = null;
			String[] headersArr = headersString.split("\n");
			for (String header : headersArr) {
			    String[] headerToken = header.split(":");
			    String headerName = headerToken[0];
			    String headerValue = headerToken[1].trim();

			    headerDTO = new RfHeaderDTO();
			    headerDTO.setHeaderName(headerName);
			    headerDTO.setHeaderValue(headerValue);
			    headerDTOs.add(headerDTO);
			}
			rfRequestDTO.setHeaders(headerDTOs);
		    }

		    String dataMode = request.getString("dataMode");
		    if ("raw".equals(dataMode)) {
			String rawModeData = request.getString("rawModeData");
			rfRequestDTO.setApiBody(rawModeData);
		    } else if ("params".equals(dataMode)) {
			JSONArray formParamsArr = request.getJSONArray("data");
			int arrLen = formParamsArr.length();

			FormDataDTO formParam = null;
			List<FormDataDTO> formParams = new ArrayList<FormDataDTO>();
			for (int j = 0; j < arrLen; j++) {
			    JSONObject formParamJSON = (JSONObject) formParamsArr.get(j);
			    formParam = new FormDataDTO();
			    formParam.setKey(formParamJSON.getString("key"));
			    formParam.setValue(formParamJSON.getString("value"));
			    formParams.add(formParam);
			}
			rfRequestDTO.setFormParams(formParams);
		    }

		    conversationDTO.setRfRequestDTO(rfRequestDTO);
		    Conversation createdConversation = conversationController.create(conversationDTO);
		    conversationDTO.setId(createdConversation.getId());

		    // Request Node
		    NodeDTO childNode = new NodeDTO();
		    childNode.setName(requestName);
		    childNode.setDescription(requestDescription);
		    childNode.setProjectId(projectId);
		    childNode.setConversationDTO(conversationDTO);
		    BaseNode createdChildNode = nodeController.create(collectionNode.getId(), childNode);
		    System.out.println("created node : " + createdChildNode.getName());
		}
	    } catch (Exception e) {
		logger.error(e.getMessage(), e);
	    }
	}
    }
}


text:
var Message = require('zmq-service-suite-message');

describe('metric', function() {
  var msg, log;
  var metric = require('../../lib/metric');

  beforeEach(function () {
    msg = new Message('sid', 'verb');
    msg.identity = 'some#1';
    msg.type = Message.Type.REQ;
  });

  describe('#start', function() {
    it('should return the message', function () {
      expect(metric.start(msg)).toEqual(msg);
    });

    it('should return the message when headers not present', function () {
      msg.headers = null;
      expect(metric.start(msg)).toEqual(msg);
    });

    it('should add micro.sr header', function () {
      var message = metric.start(msg);
      var expected = message.headers['micro.sr'];
      expect(expected).not.toBe(undefined);
    });
  });

  describe('#end', function() {
    it('should return the message', function () {
      expect(metric.end(msg)).toEqual(msg);
    });

    it('should return the message when headers not present', function () {
      msg.headers = null;
      expect(metric.end(msg)).toEqual(msg);
    });

    it('should add micro.ss header', function () {
      var message = metric.end(msg);
      var expected = message.headers['micro.ss'];
      expect(expected).not.toBe(undefined);
    });
  });
});


text:
package net.sf.jailer.ui.databrowser;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import net.sf.jailer.datamodel.Association;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.ui.JComboBox2;
import net.sf.jailer.ui.UIUtil;
import net.sf.jailer.util.SqlUtil;

/**
 *
 * @author RalfW
 */
public class AssociationPathPanel extends javax.swing.JPanel {

	final Association[] selectedAssociations;

    /**
     * Creates new form AssociationPathPanel
     * @param path the path
     * @param ignoredColor
     * @param assocColor
     * @param hasDepColor
     * @param depOnColor
     */
    public AssociationPathPanel(DataModel dataModel, List<Table> path, Color depOnColor, Color hasDepColor, Color assocColor, Color ignoredColor) {
        initComponents();
        Font font = new JLabel("normal").getFont();
		Font bold = font.deriveFont(font.getStyle() | Font.BOLD);

		okButton.setIcon(UIUtil.scaleIcon(okButton, okIcon));
		cancelButton.setIcon(UIUtil.scaleIcon(cancelButton, cancelIcon));

		jLabel1.setFont(bold);
		jLabel2.setFont(bold);
		jLabel3.setFont(bold);

		selectedAssociations = new Association[path.size() - 1];

		final Map<Association, Color> colorMap = new HashMap<Association, Color>();

		int y = 2;
		for (int i = path.size() - 1; i >= 0; --i) {
			final int finalI = i;
			Table table = path.get(i);
			JLabel label = new JLabel();
			label.setText(dataModel.getDisplayName(table) + "   ");
	        GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
	        gridBagConstraints.gridx = 1;
	        gridBagConstraints.gridy = y;
	        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
	        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
	        pathPanel.add(label, gridBagConstraints);

    		if (i > 0) {
        		final List<Association> associations = new ArrayList<Association>();
	    		Table to = path.get(i - 1);
	    		for (Association a: table.associations) {
	    			if (a.destination.equals(to)) {
	    				associations.add(a);
	    				Color c;
	    				if (a.isIgnored()) {
	    					c = ignoredColor;
	    				} else if (a.isInsertDestinationBeforeSource()) {
	    					c = depOnColor;
	    				} else if (a.isInsertSourceBeforeDestination()) {
	    					c = hasDepColor;
	    				} else {
	    					c = assocColor;
	    				}
	    				colorMap.put(a, c);
	    			}
	    		}
	        	Association first = associations.get(0);
	        	selectedAssociations[i - 1] = first;

				label = new JLabel();
				String jc = first.getUnrestrictedJoinCondition();
				if (first.reversed) {
					jc = SqlUtil.reversRestrictionCondition(jc);
				}
				label.setText(jc);
				label.setForeground(colorMap.get(first));
		        gridBagConstraints = new java.awt.GridBagConstraints();
		        gridBagConstraints.gridx = 3;
		        gridBagConstraints.gridy = y;
		        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
		        gridBagConstraints.weightx = 1.0;
		        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
		        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
		        pathPanel.add(label, gridBagConstraints);

		        final JLabel conditionLabel = label;

		        gridBagConstraints = new java.awt.GridBagConstraints();
		        gridBagConstraints.gridx = 2;
		        gridBagConstraints.gridy = y;
		        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
		        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);

		        if (associations.size() == 1) {
					label = new JLabel();
					label.setText(associations.get(0).getName() + "   ");
					label.setForeground(colorMap.get(first));
			        pathPanel.add(label, gridBagConstraints);
	        	} else {
	        		needToAsk = true;
	        		Vector<String> model = new Vector<String>();
	        		for (Association a: associations) {
	        			model.add(a.getName());
	        		}
	        		final JComboBox2 comboBox = new JComboBox2(model);
	        		comboBox.setSelectedIndex(0);
	        		comboBox.addItemListener(new ItemListener() {
						@Override
						public void itemStateChanged(ItemEvent e) {
							int si = comboBox.getSelectedIndex();
							if (si >= 0) {
								Association association = associations.get(si);
								selectedAssociations[finalI - 1] = association;
								String jc = association.getUnrestrictedJoinCondition();
								if (association.reversed) {
									jc = SqlUtil.reversRestrictionCondition(jc);
								}
								conditionLabel.setText(jc);
								conditionLabel.setForeground(colorMap.get(association));
							}
						}
					});
	        		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
	        		pathPanel.add(comboBox, gridBagConstraints);
	        	}
    		}

	        ++y;
		}
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        pathPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        dummyPanel = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setLayout(new java.awt.GridBagLayout());

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));

        pathPanel.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Table ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        pathPanel.add(jLabel1, gridBagConstraints);

        jLabel2.setText("Association ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        pathPanel.add(jLabel2, gridBagConstraints);

        jLabel3.setText("Condition");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        pathPanel.add(jLabel3, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        pathPanel.add(jSeparator1, gridBagConstraints);

        javax.swing.GroupLayout dummyPanelLayout = new javax.swing.GroupLayout(dummyPanel);
        dummyPanel.setLayout(dummyPanelLayout);
        dummyPanelLayout.setHorizontalGroup(
            dummyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        dummyPanelLayout.setVerticalGroup(
            dummyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 300;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.weighty = 1.0;
        pathPanel.add(dummyPanel, gridBagConstraints);

        jScrollPane1.setViewportView(pathPanel);

        jPanel1.add(jScrollPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(jPanel1, gridBagConstraints);

        jPanel2.setLayout(new java.awt.GridBagLayout());

        okButton.setText("Open Path");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 1.0;
        jPanel2.add(okButton, gridBagConstraints);

        cancelButton.setText("Cancel");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
        jPanel2.add(cancelButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        add(jPanel2, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton cancelButton;
    private javax.swing.JPanel dummyPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    public javax.swing.JButton okButton;
    private javax.swing.JPanel pathPanel;
    // End of variables declaration//GEN-END:variables

    protected boolean needToAsk = false;
    protected boolean ok = false;

	private static ImageIcon okIcon;
	private static ImageIcon cancelIcon;

	static {
        // load images
        okIcon = UIUtil.readImage("/buttonok.png");
        cancelIcon = UIUtil.readImage("/buttoncancel.png");
	}
}


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2;
/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType IdentifierType
 * @xmlName NetworkIDType
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\NetworkIDType
 */
class NetworkIDType
	extends _2\IdentifierType
	{

} // end class NetworkIDType


text:
cask v1: 'macdrops' do
  version '1.1'
  sha256 'c91f10418d8dd88f395603f9b824fc1ef319ec91affe2326cff5bce7f2bd63bb'

  url "https://interfacelift.com/apps/macdrops/v1/Macdrops_v#{version}.dmg"
  name 'Macdrops'
  homepage 'https://interfacelift.com/apps/macdrops/v1'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app "Macdrops v#{version}.app"
end


text:
namespace GroupDocs.Viewer.WebForm.FrontEnd.BusinessLayer
{
    public class GetResourceForHtmlParameters
    {
        public string DocumentPath { get; set; }
        public string ResourceName { get; set; }
        public int PageNumber { get; set; }
    }
}


text:
Prerequisite: install node.js, install TypeScript globally:

    npm install -g typescript

Prerequisite: Visual Studio 2015 Update 3 or Visual Studio 2017

Prerequisite: Configure Visual Studio to use the global external web tools instead of the tools that ship with Visual Studio:
  - Open the Options dialog with Tools | Options
  - In the tree on the left, select Projects and Solutions | External Web Tools.
  - On the right, move the $(PATH) entry above the $(DevEnvDir) entries. This tells Visual Studio to use the external tools (such as npm) found in the global path before using its own version of the external tools.
  - Click OK to close the dialog.
  - Restart Visual Studio for this change to take effect.

To disable compilation of ts files in IDE upon saving set for a given tsconfig.json "compileOnSave": false

If you want to disable "npm install" every time you open the project then turn off all entries in External Web Tools.

If you would like to disable building TypeScript files by IDE Build in your solution add node
```sh
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
```
to the first PropertyGroup element in .csproj file.

# Building Angular:
First install all npm packages:

    npm install

Build your Angular app by npm scripts commands:

| npm script | comment |
| ------ | ------ |
| npm run build  | build Angular app without AOT |
| npm run build:prod | build Angular app for production with AOT and minimization |
| npm run wp  | build Angular app in watch mode without AOT |
| npm run wp:aot | build Angular app with AOT but not in production mode |
| npm run clean | clean output webpack folder |
| npm run reset  | clean everything including node_modules |
| npm run tslint  | inting Angular app |
| npm run test  | testing Angular app by karma and jasmine |
| npm run e2e  | e2e testing Angular app by protractor |
| npm run srcmap  | investigate resulting webpack chunck, change for correct filename |

All routes redirected to Angular app except for /api , /oauth , /signalr uri. If you want to add routes to WebApi, then add corresponding line in Web.config rule named "Angular routes", e.g.
```sh
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true"/>
```

 Project support angular-cli generation, testing and linting.

 Go to ./src/app folder and run for example

    ng generate component test

 It require to install angular-cli globally:

    npm install -g @angular/cli

# Authentication

This application use JWT authentication.  Call /oauth/token endpoint for authentication.

Add to the project root folder keys.config file with secret key for signing tokens. **Don't include it to the source control**. Example:
```sh
<appSettings>
  <add key="issuer" value="http://localhost:62422/"/>
  <add key="secret" value="IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"/>
  <add key="as:AudienceId" value="414e1927a3884f68abc79f7283837fd1" />
</appSettings>
```

This application use basic realization of Identity framework without EntityFrameowork or any other real DB. You can change working logic with DB in CustomUserManager and CustomUserStore classes.

Use BCrypt for password hashing in BCryptPasswordHasher class.

# Useful extensions:

For integration webpack builds with Studio building process use [NPM Task Runner](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner)

Or [WebPack Task Runner](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebPackTaskRunner)

There is example of custom button, which will toggle Webpack's watch mode on and off in Visual Studio 2015 [link](https://github.com/webpack/docs/wiki/Usage-with-Visual-Studio)

You can use [WebAnalyzer](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebAnalyzer) for tslint.

This extension allow you to copy C# source code, then paste as Typescript syntax which help you with converting DTO or interface [TypescriptSyntaxPaste](https://marketplace.visualstudio.com/items?itemName=NhaBuiDuc.TypescriptSyntaxPaste)


text:
__author__ = 'VinnieJohns'
from sys import maxsize

class Group:

    def __init__(self, name=None, header=None, footer=None, id=None):
        self.name = name
        self.header = header
        self.footer = footer
        self.id = id

    def __repr__(self):
        return "{id}:{name};{header};{footer}".format(id=self.id, name=self.name, header=self.header, footer=self.footer)

    def __eq__(self, other):
        return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name

    def id_or_max(self):
        if self.id:
            return int(self.id)
        else:
            return maxsize


text:
require 'yaml'

module SecretAgentNoun
  class << self
    def agent_noun(verb)
      lookup[normalize(verb)]
    end

    def verb(agent_noun)
      inverse_lookup[normalize(agent_noun)]
    end

    private

    def yaml_file
      File.expand_path('../../db/verbs_to_agent_nouns.yml', __FILE__)
    end

    def lookup
      @lookup ||= YAML.load_file(yaml_file)
    end

    def inverse_lookup
      @inverse_lookup ||= lookup.invert
    end

    def normalize(input)
      input.to_s.downcase
    end
  end
end


text:
Manual step

Click text input/textarea

Type text

<input class="sample" placeholder="edit me!" value="">

<textarea class="sample" placeholder="edit me!" ></textarea>


text:
<?php
namespace CristianPontes\ZohoCRMClient\Exception;

class RuntimeException extends \RuntimeException
{

}


text:
package com.khipu.lib.java;

import com.khipu.lib.java.exception.KhipuException;
import com.khipu.lib.java.exception.KhipuJSONException;
import com.khipu.lib.java.response.KhipuResponse;
import com.khipu.lib.java.response.KhipuSetPayedByReceiverResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Servicio para que el cobrador modificar el estado de un pago a realizado.
 *
 * @author Alejandro Vera (alejandro.vera@khipu.com)
 * @version 1.2
 * @since 2013-05-24
 */
public class KhipuSetPayedByReceiver extends KhipuService {

    private String _paymentId;

    public String getPaymentId() {
        return _paymentId;
    }

    public void setPaymentId(String paymentId) {
        _paymentId = paymentId;
    }

    KhipuSetPayedByReceiver(long receiverId, String secret) {
        super(receiverId, secret);
    }

    String getMethodEndpoint() {
        return "setPayedByReceiver";
    }

    public KhipuResponse execute() throws KhipuException, IOException {
        Map map = new HashMap();
        map.put("receiver_id", "" + getReceiverId());
        map.put("payment_id", "" + getPaymentId());
        map.put("hash", HmacSHA256(getSecret(), getConcatenated()));
        try {
            post(map);
            return new KhipuSetPayedByReceiverResponse();
        } catch (KhipuJSONException e) {
            throw Khipu.getErrorsException(e.getJSON());
        }
    }

    private String getConcatenated() {
        return new StringBuilder("receiver_id=").append(getReceiverId()).append("&payment_id=").append(getPaymentId()).toString();
    }
}


text:
import { mock, noop } from 'angular';

import { mockHttpClient } from '../api/mock/jasmine';
import type { MockHttpClient } from '../api/mock/mockHttpClient';
import { Application } from '../application/application.model';
import { ApplicationModelBuilder } from '../application/applicationModel.builder';
import { ApplicationDataSourceRegistry } from '../application/service/ApplicationDataSourceRegistry';
import type {
  IServerGroupCommand,
  IServerGroupCommandViewState,
} from './configure/common/serverGroupCommandBuilder.service';
import type { ServerGroupWriter } from './serverGroupWriter.service';
import { SERVER_GROUP_WRITER } from './serverGroupWriter.service';
import type { ITaskCommand } from '../task/taskExecutor';

interface IApplicationTask {
  refresh: () => void;
}

class TestApplication extends Application {
  public tasks: IApplicationTask;
}

describe('serverGroupWriter', function () {
  let serverGroupTransformer: any, serverGroupWriter: ServerGroupWriter;

  beforeEach(mock.module(SERVER_GROUP_WRITER));

  beforeEach(function () {
    mock.inject(function (_serverGroupWriter_: ServerGroupWriter, _serverGroupTransformer_: any) {
      serverGroupWriter = _serverGroupWriter_;
      serverGroupTransformer = _serverGroupTransformer_;
    });
  });

  beforeEach(function () {
    spyOn(serverGroupTransformer, 'convertServerGroupCommandToDeployConfiguration').and.callFake((command: any) => {
      return command;
    });
  });

  it('should inject defined objects', async function () {
    expect(serverGroupTransformer).toBeDefined();
    expect(serverGroupWriter).toBeDefined();
  });

  describe('clone server group submit', function () {
    async function postTask(http: MockHttpClient, serverGroupCommand: IServerGroupCommand): Promise<ITaskCommand> {
      let submitted: ITaskCommand = {};
      http
        .expectPOST(`/tasks`)
        .respond(200, { ref: '/1' })
        .onRequestReceived((resp) => (submitted = resp.data));

      const application: TestApplication = ApplicationModelBuilder.createApplicationForTests(
        'app',
        ...ApplicationDataSourceRegistry.getDataSources(),
      ) as TestApplication;
      application.tasks = {
        refresh: noop,
      };

      http.expectGET('/tasks/1').respond(200, {});
      serverGroupWriter.cloneServerGroup(serverGroupCommand, application);
      await http.flush();

      return submitted;
    }

    let command: IServerGroupCommand;
    beforeEach(() => {
      const application: Application = ApplicationModelBuilder.createApplicationForTests(
        'app',
        ...ApplicationDataSourceRegistry.getDataSources(),
      );
      command = {
        viewState: {
          mode: 'create',
        },
        application: application.name,
      } as IServerGroupCommand;
    });

    it('sets action type and description appropriately when creating new', async function () {
      const http = mockHttpClient();
      const submitted: ITaskCommand = await postTask(http, command);
      expect(submitted.job[0].type).toBe('createServerGroup');
      expect(submitted.description).toBe('Create New Server Group in cluster app');
    });

    it('sets action type and description appropriately when creating new', async function () {
      const http = mockHttpClient();
      command.stack = 'main';
      const submitted: ITaskCommand = await postTask(http, command);
      expect(submitted.description).toBe('Create New Server Group in cluster app-main');
    });

    it('sets action type and description appropriately when creating new', async function () {
      const http = mockHttpClient();
      command.stack = 'main';
      command.freeFormDetails = 'details';
      const submitted: ITaskCommand = await postTask(http, command);
      expect(submitted.description).toBe('Create New Server Group in cluster app-main-details');
    });

    it('sets action type and description appropriately when creating new', async function () {
      const http = mockHttpClient();
      command.freeFormDetails = 'details';
      const submitted: ITaskCommand = await postTask(http, command);
      expect(submitted.description).toBe('Create New Server Group in cluster app--details');
    });

    it('sets action type and description appropriately when cloning, preserving source', async function () {
      const http = mockHttpClient();
      command.source = {
        asgName: 'app-v002',
      };
      command.viewState = {
        mode: 'clone',
      } as IServerGroupCommandViewState;

      const submitted: ITaskCommand = await postTask(http, command);
      expect(submitted.job[0].type).toBe('cloneServerGroup');
      expect(submitted.description).toBe('Create Cloned Server Group from app-v002');
      expect(submitted.job[0].source).toEqual(command.source);
    });
  });
});


text:
package ariba.util.expr;

import ariba.util.core.Fmt;
import ariba.util.fieldtype.FieldInfo;
import ariba.util.fieldtype.TypeInfo;
import ariba.util.fieldvalue.Expression;
import java.util.List;

/**
    @aribaapi private
*/
public class SafeSymbolValidator extends SymbolValidator
{

   /////////////////////////////////////////////////////////////////

   public SafeSymbolValidator (Environment env,
                         Expression expression,
                         List errorCollector)
    {
        super(env, expression, errorCollector);
    }

    ////////////////////////////////////////////////////////////////////////

    protected void validate (FieldInfo field, int usage)
    {
        int fieldAccess = field.getAccessibility();
        if (fieldAccess < TypeInfo.AccessibilitySafe) {
            addError(field, Fmt.S("Field is not safe: %s", field.getName()));
        }
    }
}


text:
package org.codehaus.mojo.versions;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.mojo.versions.api.ArtifactVersions;
import org.codehaus.mojo.versions.api.PomHelper;
import org.codehaus.mojo.versions.ordering.VersionComparator;
import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader;

import javax.xml.stream.XMLStreamException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Replaces any release versions with the latest snapshot version (if it has been deployed).
 *
 * @author Stephen Connolly
 * @goal use-latest-snapshots
 * @requiresProject true
 * @requiresDirectInvocation true
 * @since 1.0-beta-1
 */
public class UseLatestSnapshotsMojo
    extends AbstractVersionsDependencyUpdaterMojo
{

    /**
     * Whether to allow the major version number to be changed.
     * @parameter expression="${allowMajorUpdates}" default-value="false"
     * @since 1.0-beta-1
     */
    protected Boolean allowMajorUpdates;

    /**
     * Whether to allow the minor version number to be changed.
     * @parameter expression="${allowMinorUpdates}" default-value="false"
     * @since 1.0-beta-1
     */
    protected Boolean allowMinorUpdates;

    /**
     * Whether to allow the incremental version number to be changed.
     * @parameter expression="${allowIncrementalUpdates}" default-value="true"
     * @since 1.0-beta-1
     */
    protected Boolean allowIncrementalUpdates;

    // ------------------------------ FIELDS ------------------------------

    /**
     * Pattern to match a snapshot version.
     */
    public final Pattern matchSnapshotRegex = Pattern.compile( "^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$" );

    // ------------------------------ METHODS --------------------------

    /**
     * @param pom the pom to update.
     * @throws org.apache.maven.plugin.MojoExecutionException
     *          when things go wrong
     * @throws org.apache.maven.plugin.MojoFailureException
     *          when things go wrong in a very bad way
     * @throws javax.xml.stream.XMLStreamException
     *          when things go wrong with XML streaming
     * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader)
     */
    protected void update( ModifiedPomXMLEventReader pom )
        throws MojoExecutionException, MojoFailureException, XMLStreamException
    {
        try
        {
            if ( getProject().getDependencyManagement() != null && isProcessingDependencyManagement() )
            {
                useLatestSnapshots( pom, getProject().getDependencyManagement().getDependencies() );
            }
            if ( isProcessingDependencies() )
            {
                useLatestSnapshots( pom, getProject().getDependencies() );
            }
        }
        catch ( ArtifactMetadataRetrievalException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }

    private void useLatestSnapshots( ModifiedPomXMLEventReader pom, Collection dependencies )
        throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException
    {
        int segment = determineUnchangedSegment(allowMajorUpdates, allowMinorUpdates,
                allowIncrementalUpdates);

        Iterator i = dependencies.iterator();

        while ( i.hasNext() )
        {
            Dependency dep = (Dependency) i.next();

            if ( isExcludeReactor() && isProducedByReactor( dep ) )
            {
                getLog().info( "Ignoring reactor dependency: " + toString( dep ) );
                continue;
            }

            String version = dep.getVersion();
            Matcher versionMatcher = matchSnapshotRegex.matcher( version );
            if ( !versionMatcher.matches() )
            {
                getLog().debug( "Looking for latest snapshot of " + toString( dep ) );
                Artifact artifact = this.toArtifact( dep );
                if ( !isIncluded( artifact ) )
                {
                    continue;
                }

                ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false );
                final VersionComparator versionComparator = versions.getVersionComparator();
                final DefaultArtifactVersion lowerBound = new DefaultArtifactVersion( version );
                if ( segment + 1 > versionComparator.getSegmentCount( lowerBound ) )
                {
                    getLog().info( "Ignoring " + toString( dep ) + " as the version number is too short" );
                    continue;
                }
                ArtifactVersion upperBound = segment >= 0 ? versionComparator.incrementSegment( lowerBound, segment ) : null;
                getLog().info("Upper bound: " + upperBound.toString());
                ArtifactVersion[] newer = versions.getVersions( lowerBound, upperBound, true, false, false );
                getLog().debug( "Candidate versions " + Arrays.asList(newer));
                String latestVersion = null;
                for ( int j = 0; j < newer.length; j++ )
                {
                    String newVersion = newer[j].toString();
                    if ( matchSnapshotRegex.matcher( newVersion ).matches() )
                    {
                        latestVersion = newVersion;
                    }
                }
                if ( latestVersion != null )
                {
                    if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), version,
                                                         latestVersion ) )
                    {
                        getLog().info( "Updated " + toString( dep ) + " to version " + latestVersion );
                    }
                }
            }
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<Component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="3aa0a9d2-1dc1-4aee-890d-e4c2491613e3" Name="drawbar_bolted__bp__orthogonal_27216kg" Version="" xmlns="avm">
  <DomainModel xmlns:q1="cad" xsi:type="q1:CADModel" UsesResource="cad.path" FilePathWithinResource="e247_db_bolt_bp_o_27216kgz3z" Author="" Notes="" xmlns="">
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_04" PortMap="" Name="INT_BOLT_04" Notes="" Definition="" DatumName="INT_BOLT_04" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_07" PortMap="" Name="INT_BOLT_07" Notes="" Definition="" DatumName="INT_BOLT_07" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_06" PortMap="" Name="INT_BOLT_06" Notes="" Definition="" DatumName="INT_BOLT_06" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_05" PortMap="" Name="INT_BOLT_05" Notes="" Definition="" DatumName="INT_BOLT_05" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_08" PortMap="" Name="INT_BOLT_08" Notes="" Definition="" DatumName="INT_BOLT_08" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.CG_CSYS" PortMap="" Name="CG_CSYS" Notes="" Definition="" DatumName="CG_CSYS" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.BDB1385_ASM" PortMap="" Name="BDB1385_ASM" Notes="" Definition="" DatumName="BDB1385_ASM" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.EXT_MOUNT_1" PortMap="" Name="EXT_MOUNT_1" Notes="" Definition="" DatumName="EXT_MOUNT_1" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_03" PortMap="" Name="INT_BOLT_03" Notes="" Definition="" DatumName="INT_BOLT_03" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_LOAD_LOCATION" PortMap="" Name="INT_LOAD_LOCATION" Notes="" Definition="" DatumName="INT_LOAD_LOCATION" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_01" PortMap="" Name="INT_BOLT_01" Notes="" Definition="" DatumName="INT_BOLT_01" />
    <Datum xsi:type="q1:CoordinateSystem" ID="cad.INT_BOLT_02" PortMap="" Name="INT_BOLT_02" Notes="" Definition="" DatumName="INT_BOLT_02" />
    <Datum xsi:type="q1:Plane" ID="cad.DTM4" PortMap="" Name="DTM4" Notes="" Definition="" DatumName="DTM4" />
    <Datum xsi:type="q1:Plane" ID="cad.DTM2" PortMap="" Name="DTM2" Notes="" Definition="" DatumName="DTM2" />
    <Datum xsi:type="q1:Axis" ID="cad.A_9" PortMap="" Name="A_9" Notes="" Definition="" DatumName="A_9" />
    <Parameter Name="TestParam">
      <Value DataType="Real" Unit="mm">
        <ValueExpression xmlns:q2="avm" xsi:type="q2:FixedValue">
          <Value>123456</Value>
        </ValueExpression>
      </Value>
    </Parameter>
    <Parameter Name="TOTAL_MASS">
      <Value DataType="Real" Unit="kg" ID="cad.TOTAL_MASS">
        <ValueExpression xmlns:q3="avm" xsi:type="q3:FixedValue">
          <Value>8.437</Value>
        </ValueExpression>
      </Value>
    </Parameter>
    <ModelMetric ID="ID4" Name="moment_of_inertia">
      <Value>
        <ValueExpression xmlns:q4="avm" xsi:type="q4:FixedValue">
          <Value>[[0.0285702605965938,0,0],[0,0.0372253947417373,5.64682725439304e-007],[0,5.64682725439304e-007,0.0232466676899066]]</Value>
        </ValueExpression>
      </Value>
    </ModelMetric>
  </DomainModel>
  <Property xmlns:q5="avm" xsi:type="q5:PrimitiveProperty" Name="unit_of_measure_other" ID="property.nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_other" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_other">
      <ValueExpression xsi:type="q5:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q6="avm" xsi:type="q6:PrimitiveProperty" Name="width" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.width" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.width">
      <ValueExpression xsi:type="q6:FixedValue">
        <Value>0.192375</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q7="avm" xsi:type="q7:PrimitiveProperty" Name="unit_of_measure_area" ID="property.nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_area" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_area">
      <ValueExpression xsi:type="q7:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q8="avm" xsi:type="q8:PrimitiveProperty" Name="supplier_part_number" ID="property.nv.procurement.supplier_specific_part_info.supplier_part_number" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.supplier_part_number">
      <ValueExpression xsi:type="q8:FixedValue">
        <Value>BDB1394</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q9="avm" xsi:type="q9:PrimitiveProperty" Name="supplier_part_description" ID="property.nv.procurement.supplier_specific_part_info.supplier_part_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.supplier_part_description">
      <ValueExpression xsi:type="q9:FixedValue">
        <Value>Heavy-Duty Forged 4-Bolt Mount Drawbar</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q10="avm" xsi:type="q10:PrimitiveProperty" Name="shipping_cost" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipping_cost" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipping_cost">
      <ValueExpression xsi:type="q10:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q11="avm" xsi:type="q11:PrimitiveProperty" Name="country_name" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.country_name" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.country_name">
      <ValueExpression xsi:type="q11:FixedValue">
        <Value>USA</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q12="avm" xsi:type="q12:PrimitiveProperty" Name="state_region_name" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.state_region_name" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.state_region_name">
      <ValueExpression xsi:type="q12:FixedValue">
        <Value>OH</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q13="avm" xsi:type="q13:PrimitiveProperty" Name="height" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.height" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.height">
      <ValueExpression xsi:type="q13:FixedValue">
        <Value>0.210375</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q14="avm" xsi:type="q14:PrimitiveProperty" Name="town_city_name" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.town_city_name" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.town_city_name">
      <ValueExpression xsi:type="q14:FixedValue">
        <Value>Mentor</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q15="avm" xsi:type="q15:PrimitiveProperty" Name="unit_of_measure_length" ID="property.nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_length" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_length">
      <ValueExpression xsi:type="q15:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q16="avm" xsi:type="q16:PrimitiveProperty" Name="cots_or_parametric" ID="property.nv.procurement.cots_or_parametric" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.cots_or_parametric">
      <ValueExpression xsi:type="q16:FixedValue">
        <Value>COTS</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q17="avm" xsi:type="q17:PrimitiveProperty" Name="nsn" ID="property.nv.procurement.nsn" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.nsn">
      <ValueExpression xsi:type="q17:FixedValue">
        <Value>none</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q18="avm" xsi:type="q18:PrimitiveProperty" Name="make_or_buy" ID="property.nv.procurement.make_or_buy" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.make_or_buy">
      <ValueExpression xsi:type="q18:FixedValue">
        <Value>Buy</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q19="avm" xsi:type="q19:PrimitiveProperty" Name="street_name" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.street_name" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.street_name">
      <ValueExpression xsi:type="q19:FixedValue">
        <Value>Tyler Blvd</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q20="avm" xsi:type="q20:PrimitiveProperty" Name="zip_postal_code" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.zip_postal_code" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Integer" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.zip_postal_code">
      <ValueExpression xsi:type="q20:FixedValue">
        <Value>44060</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q21="avm" xsi:type="q21:PrimitiveProperty" Name="msds" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.msds" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.msds">
      <ValueExpression xsi:type="q21:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q22="avm" xsi:type="q22:PrimitiveProperty" Name="dunnage" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.dunnage" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.dunnage">
      <ValueExpression xsi:type="q22:FixedValue">
        <Value>Recycle</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q23="avm" xsi:type="q23:PrimitiveProperty" Name="mass_shipping_wet" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.mass_shipping_wet" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.mass_shipping_wet">
      <ValueExpression xsi:type="q23:FixedValue">
        <Value>10.54625</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q24="avm" xsi:type="q24:PrimitiveProperty" Name="mass_shipping_dry" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.mass_shipping_dry" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.mass_shipping_dry">
      <ValueExpression xsi:type="q24:FixedValue">
        <Value>10.54625</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q25="avm" xsi:type="q25:PrimitiveProperty" Name="length" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.length" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.shipment_dimensions.length">
      <ValueExpression xsi:type="q25:FixedValue">
        <Value>0.218125</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q26="avm" xsi:type="q26:PrimitiveProperty" Name="street_number" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.street_number" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Integer" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.default_ship_from_address.street_number">
      <ValueExpression xsi:type="q26:FixedValue">
        <Value>9049</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q27="avm" xsi:type="q27:PrimitiveProperty" Name="fob" ID="property.nv.procurement.supplier_specific_part_info.part_info.shipping_info.fob" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.shipping_info.fob">
      <ValueExpression xsi:type="q27:FixedValue">
        <Value>Origin</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q28="avm" xsi:type="q28:PrimitiveProperty" Name="unit_of_measure_volume" ID="property.nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_volume" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.orderable_unit.unit_of_measure_volume">
      <ValueExpression xsi:type="q28:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q29="avm" xsi:type="q29:PrimitiveProperty" Name="part_leadtime" ID="property.nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_leadtime" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_leadtime">
      <ValueExpression xsi:type="q29:FixedValue">
        <Value>0.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q30="avm" xsi:type="q30:PrimitiveProperty" Name="dependants.acceleration" ID="property.nv.procurement.qualification_info.vibration_qualification.breakpoint_graph.dependants.acceleration" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.breakpoint_graph.dependants.acceleration">
      <ValueExpression xsi:type="q30:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q31="avm" xsi:type="q31:PrimitiveProperty" Name="shape" ID="property.nv.procurement.qualification_info.shock_qualification.shape" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.shape">
      <ValueExpression xsi:type="q31:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q32="avm" xsi:type="q32:PrimitiveProperty" Name="duration" ID="property.nv.procurement.qualification_info.shock_qualification.duration" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.duration">
      <ValueExpression xsi:type="q32:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q33="avm" xsi:type="q33:PrimitiveProperty" Name="frequency_range" ID="property.nv.procurement.qualification_info.vibration_qualification.frequency_range" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.frequency_range">
      <ValueExpression xsi:type="q33:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q34="avm" xsi:type="q34:PrimitiveProperty" Name="currency" ID="property.nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_cost_tooling.currency" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_cost_tooling.currency">
      <ValueExpression xsi:type="q34:FixedValue">
        <Value>usd</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q35="avm" xsi:type="q35:PrimitiveProperty" Name="independant.frequency" ID="property.nv.procurement.qualification_info.vibration_qualification.breakpoint_graph.independant.frequency" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.breakpoint_graph.independant.frequency">
      <ValueExpression xsi:type="q35:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q36="avm" xsi:type="q36:PrimitiveProperty" Name="vibration_qualification_type" ID="property.nv.procurement.qualification_info.vibration_qualification.vibration_qualification_type" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.vibration_qualification_type">
      <ValueExpression xsi:type="q36:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q37="avm" xsi:type="q37:PrimitiveProperty" Name="quantity_parts_per_unit" ID="property.nv.procurement.supplier_specific_part_info.part_info.orderable_unit.quantity_parts_per_unit" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.orderable_unit.quantity_parts_per_unit">
      <ValueExpression xsi:type="q37:FixedValue">
        <Value>1.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q38="avm" xsi:type="q38:PrimitiveProperty" Name="storage_temperature_low" ID="property.nv.procurement.qualification_info.temperature_qualification.storage_temperature_low" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.temperature_qualification.storage_temperature_low">
      <ValueExpression xsi:type="q38:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q39="avm" xsi:type="q39:PrimitiveProperty" Name="volume_basis_part_cost" ID="property.nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.volume_basis_part_cost" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Integer" ID="nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.volume_basis_part_cost">
      <ValueExpression xsi:type="q39:FixedValue">
        <Value>1</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q40="avm" xsi:type="q40:PrimitiveProperty" Name="max_amplitude_rms" ID="property.nv.procurement.qualification_info.vibration_qualification.max_amplitude_rms" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.max_amplitude_rms">
      <ValueExpression xsi:type="q40:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q41="avm" xsi:type="q41:PrimitiveProperty" Name="storage_temperature_high" ID="property.nv.procurement.qualification_info.temperature_qualification.storage_temperature_high" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.temperature_qualification.storage_temperature_high">
      <ValueExpression xsi:type="q41:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q42="avm" xsi:type="q42:PrimitiveProperty" Name="max_amplitude_zero_to_peak" ID="property.nv.procurement.qualification_info.vibration_qualification.max_amplitude_zero_to_peak" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.vibration_qualification.max_amplitude_zero_to_peak">
      <ValueExpression xsi:type="q42:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q43="avm" xsi:type="q43:PrimitiveProperty" Name="operating_temperature_low" ID="property.nv.procurement.qualification_info.temperature_qualification.operating_temperature_low" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.temperature_qualification.operating_temperature_low">
      <ValueExpression xsi:type="q43:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q44="avm" xsi:type="q44:PrimitiveProperty" Name="operating_temperature_high" ID="property.nv.procurement.qualification_info.temperature_qualification.operating_temperature_high" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.temperature_qualification.operating_temperature_high">
      <ValueExpression xsi:type="q44:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q45="avm" xsi:type="q45:PrimitiveProperty" Name="shock_qualification_type" ID="property.nv.procurement.qualification_info.shock_qualification.shock_qualification_type" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.shock_qualification_type">
      <ValueExpression xsi:type="q45:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q46="avm" xsi:type="q46:PrimitiveProperty" Name="rrs_shape" ID="property.nv.procurement.qualification_info.shock_qualification.rrs_shape" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.rrs_shape">
      <ValueExpression xsi:type="q46:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q47="avm" xsi:type="q47:PrimitiveProperty" Name="value" ID="property.nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_cost_tooling.value" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.procurement.supplier_specific_part_info.part_info.cost_leadtime_prototype.part_cost_tooling.value">
      <ValueExpression xsi:type="q47:FixedValue">
        <Value>0.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q48="avm" xsi:type="q48:PrimitiveProperty" Name="manufacturer_part_number" ID="property.nv.procurement.manufacturer_part_info.manufacturer_part_number" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.manufacturer_part_info.manufacturer_part_number">
      <ValueExpression xsi:type="q48:FixedValue">
        <Value>BDB1394</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q49="avm" xsi:type="q49:PrimitiveProperty" Name="x" ID="property.nv.load_rating.x" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.load_rating.x">
      <ValueExpression xsi:type="q49:FixedValue">
        <Value>84516.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q50="avm" xsi:type="q50:PrimitiveProperty" Name="manufacturer_part_description" ID="property.nv.procurement.manufacturer_part_info.manufacturer_part_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.procurement.manufacturer_part_info.manufacturer_part_description">
      <ValueExpression xsi:type="q50:FixedValue">
        <Value>Heavy-Duty Forged 4-Bolt Mount Drawbar</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q51="avm" xsi:type="q51:PrimitiveProperty" Name="load" ID="property.nv.load" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.load">
      <ValueExpression xsi:type="q51:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q52="avm" xsi:type="q52:PrimitiveProperty" Name="surface_area" ID="property.nv.common_info.surface_area" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.common_info.surface_area">
      <ValueExpression xsi:type="q52:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q53="avm" xsi:type="q53:PrimitiveProperty" Name="origin_description" ID="property.nv.common_info.origin_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.common_info.origin_description">
      <ValueExpression xsi:type="q53:FixedValue">
        <Value>along vertical centerline of eye, in the center of eye thickness, below the bottom of the opening</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q54="avm" xsi:type="q54:PrimitiveProperty" Name="damping_ratio" ID="property.nv.procurement.qualification_info.shock_qualification.damping_ratio" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.damping_ratio">
      <ValueExpression xsi:type="q54:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q55="avm" xsi:type="q55:PrimitiveProperty" Name="z" ID="property.nv.load_rating.z" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.load_rating.z">
      <ValueExpression xsi:type="q55:FixedValue">
        <Value>400340.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q56="avm" xsi:type="q56:PrimitiveProperty" Name="operating_condition_description" ID="property.nv.common_info.operating_condition_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.common_info.operating_condition_description">
      <ValueExpression xsi:type="q56:FixedValue">
        <Value>can operate in all mounting directions</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q57="avm" xsi:type="q57:PrimitiveProperty" Name="I_zz" ID="property.nv.common_info.moment_of_inertia.I_zz" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_zz">
      <ValueExpression xsi:type="q57:FixedValue">
        <Value>0.02325</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q58="avm" xsi:type="q58:PrimitiveProperty" Name="I_xx" ID="property.nv.common_info.moment_of_inertia.I_xx" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_xx">
      <ValueExpression xsi:type="q58:FixedValue">
        <Value>0.02857</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q59="avm" xsi:type="q59:PrimitiveProperty" Name="orientation_description" ID="property.nv.common_info.orientation_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="String" ID="nv.common_info.orientation_description">
      <ValueExpression xsi:type="q59:FixedValue">
        <Value>positive x-axis is parallel with the bolt hole centerlines, z-axis is parallel with eye centerline</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q60="avm" xsi:type="q60:PrimitiveProperty" Name="I_zy" ID="property.nv.common_info.moment_of_inertia.I_zy" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_zy">
      <ValueExpression xsi:type="q60:FixedValue">
        <Value>0.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q61="avm" xsi:type="q61:PrimitiveProperty" Name="instance_description" ID="property.nv.instance_description" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.instance_description">
      <ValueExpression xsi:type="q61:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q62="avm" xsi:type="q62:PrimitiveProperty" Name="mass" ID="property.nv.common_info.mass" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.common_info.mass">
      <ValueExpression xsi:type="q62:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q63="avm" xsi:type="q63:PrimitiveProperty" Name="I_zx" ID="property.nv.common_info.moment_of_inertia.I_zx" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_zx">
      <ValueExpression xsi:type="q63:FixedValue">
        <Value>0.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q64="avm" xsi:type="q64:PrimitiveProperty" Name="y" ID="property.nv.load_rating.y" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.load_rating.y">
      <ValueExpression xsi:type="q64:FixedValue">
        <Value>84516.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q65="avm" xsi:type="q65:PrimitiveProperty" Name="I_yy" ID="property.nv.common_info.moment_of_inertia.I_yy" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_yy">
      <ValueExpression xsi:type="q65:FixedValue">
        <Value>0.03723</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q66="avm" xsi:type="q66:PrimitiveProperty" Name="I_yx" ID="property.nv.common_info.moment_of_inertia.I_yx" xmlns="">
    <Value DimensionType="Scalar" Dimensions="1" DataType="Real" ID="nv.common_info.moment_of_inertia.I_yx">
      <ValueExpression xsi:type="q66:FixedValue">
        <Value>0.0</Value>
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q67="avm" xsi:type="q67:PrimitiveProperty" Name="independant.time" ID="property.nv.procurement.qualification_info.shock_qualification.time_graph.independant.time" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.procurement.qualification_info.shock_qualification.time_graph.independant.time">
      <ValueExpression xsi:type="q67:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <Property xmlns:q68="avm" xsi:type="q68:PrimitiveProperty" Name="volume" ID="property.nv.common_info.volume" xmlns="">
    <Value DimensionType="Scalar" Dimensions="" DataType="String" ID="nv.common_info.volume">
      <ValueExpression xsi:type="q68:FixedValue">
        <Value />
      </ValueExpression>
    </Value>
  </Property>
  <ResourceDependency Name="supplier_domain.Buyers_Products.xml" Path="SUPPLIERS_VAND\" Hash="" ID="manufacturer.path" Notes="" xmlns="" />
  <ResourceDependency Name="e247_db_bolt_bp_o_27216kg.prt" Path="CAD Library\E_Hull_Frame_Body_Cab\e247_db_bolt_bp_o_27216kg.prt" Hash="" ID="cad.path" Notes="" xmlns="" />
  <Connector ConnectorComposition="" ID="conn.hook_to_hull" ApplyJoinData="" Notes="" Name="hook_to_hull" Definition="cml_zodb.cml_connectors_mechanical.CML_Connector_Mechanical" xmlns="">
    <Role xmlns:q69="cad" xsi:type="q69:Plane" ID="ID0" PortMap="" Name="3" Notes="" Definition="" />
    <Role xmlns:q70="cad" xsi:type="q70:Plane" ID="ID1" PortMap="" Name="2" Notes="" Definition="" />
    <Role xmlns:q71="cad" xsi:type="q71:Axis" ID="ID2" PortMap="" Name="1" Notes="" Definition="" />
  </Connector>
  <Connector ConnectorComposition="" ID="conn.load_location" ApplyJoinData="" Notes="" Name="load_location" Definition="cml_zodb.cml_connectors_mechanical.CML_Connector_Mechanical_Hook_Eye" xmlns="">
    <Role xmlns:q72="cad" xsi:type="q72:CoordinateSystem" ID="ID3" PortMap="cad.INT_LOAD_LOCATION" Name="" Notes="" Definition="" />
  </Connector>
  <DistributionRestriction xmlns:q73="avm" xsi:type="q73:ITAR" Notes="" Level="NotITAR" xmlns="" />
  <Classifications xmlns="">cml_zodb.usr_classes.components_hull_frame_body_cab.Drawbar_Bolted</Classifications>
</Component>


text:
class Folio::FilePlacement::SingleDocument < Folio::FilePlacement::Base
  folio_document_placement :document_placement
end

# == Schema Information
#
# Table name: folio_file_placements
#
#  id                   :bigint(8)        not null, primary key
#  placement_type       :string
#  placement_id         :bigint(8)
#  file_id              :bigint(8)
#  position             :integer
#  created_at           :datetime         not null
#  updated_at           :datetime         not null
#  type                 :string
#  title                :text
#  alt                  :string
#  placement_title      :string
#  placement_title_type :string
#
# Indexes
#
#  index_folio_file_placements_on_file_id               (file_id)
#  index_folio_file_placements_on_placement             (placement_type,placement_id)
#  index_folio_file_placements_on_placement_title       (placement_title)
#  index_folio_file_placements_on_placement_title_type  (placement_title_type)
#  index_folio_file_placements_on_type                  (type)
#


text:
let implementationPackage = "transient_json_store";
let implementationType = "t_transient_json";

load("test/templates/implementation_type/get_XXX.js.tpl");


text:
require 'net/http'
require 'uri'
require 'stringio'
require 'singleton'

class ALM::RestConnector
  include Singleton

  attr_accessor :cookies
  attr_accessor :host
  attr_accessor :port
  attr_accessor :domain
  attr_accessor :project

  def init(cookies, host, port, domain, project)
    @cookies = cookies
    @host = host
    @port = port
    @domain = domain
    @project = project
  end

  def buildEntityCollectionUrl(entityType)
    return buildUrl('qcbin/rest/domains/' + domain + '/projects/' + project + '/' + entityType + 's')
  end

  def buildDefectUrl(defectId)
    return buildUrl('qcbin/rest/domains/' + domain + '/projects/' + project + '/defects/' + defectId)
  end

  def buildUrl(path)
    return "http://#{host}:#{port}/#{path}"
  end

  def httpPut(url, data, headers)
    return doHttp('PUT', url, nil, data, headers, cookies)
  end

  def httpPost(url, data, headers)
    return doHttp('POST', url, nil, data, headers, cookies)
  end

  def httpDelete(url, headers)
    return doHttp('DELETE', url, nil, nil, headers, cookies)
  end

  def httpGet(url, queryString, headers)
    return doHttp('GET', url, queryString, nil, headers, cookies)
  end

  def httpBasicAuth(url, username, password)
    headers = {"username" => username, "password" => password}
    return doHttp('AUTH', url, nil, nil, headers, cookies)
  end

  def getCookieString
    s = StringIO.new
    if (!cookies.empty?)
      cookies.each{|key,value|
        s << key << '=' << value << ';'
      }
    end

    return s.string
  end

  private

  def doHttp(type, url, queryString, data, headers, cookies)
    if (queryString != nil && !queryString.empty?)
    	url.concat('?' + queryString)
    end

    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)

    case type
    when "POST"
      request = Net::HTTP::Post.new(uri.request_uri)
    when "GET"
      request = Net::HTTP::Get.new(uri.request_uri)
    when "PUT"
      request = Net::HTTP::Put.new(uri.request_uri)
    when "DELETE"
      request = Net::HTTP::Delete.new(uri.request_uri)
    when "AUTH"
      request = Net::HTTP::Get.new(uri.request_uri)
      request.basic_auth(headers["username"], headers["password"])
    end

    cookieString = getCookieString()
    prepareHttpRequest(request, headers, data, cookieString)

    response = http.request(request)

    res = retrieveHtmlResponse(response)
    updateCookies(res)

    return res
  end

  def prepareHttpRequest(request, headers, data, cookieString)
    contentType = nil
    if (cookieString != nil && !cookieString.empty?)
       request["Cookie"] = cookieString
    end

    if (headers != nil)
      contentType = headers.delete("Content-Type")
      headers.each{|key, value|
          request[key] = value
      }
    end

    if (data != nil)
      if (contentType != nil)
        request["Content-Type"] = contentType
        request.body = data
      end
    end
  end

  def retrieveHtmlResponse(response)
    res = ALM::Response.new
    res.statusCode = response.code
    res.responseHeaders = response
    res.responseData = response.body

    return res
  end

  def updateCookies(response)
    newCookies = response.responseHeaders.get_fields('Set-Cookie')
    if (newCookies != nil)
      newCookies.each{|cookie|
        c1 = cookie.split(';')[0]
        c2 = c1.split('=')
        key = c2[0]
        value = c2[1]
        cookies[key] = value
      }
    end
  end

end


text:
package com.yahoo.pulsar.zookeeper;

import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import org.apache.bookkeeper.test.PortManager;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.yahoo.pulsar.zookeeper.ZooKeeperClientFactory.SessionType;

@Test
public class ZookeeperClientFactoryImplTest {

    private ZookeeperServerTest localZkS;
    private ZooKeeper localZkc;
    private final int LOCAL_ZOOKEEPER_PORT = PortManager.nextFreePort();
    private final long ZOOKEEPER_SESSION_TIMEOUT_MILLIS = 5000;

    @BeforeMethod
    void setup() throws Exception {
        localZkS = new ZookeeperServerTest(LOCAL_ZOOKEEPER_PORT);
        localZkS.start();
    }

    @AfterMethod
    void teardown() throws Exception {
        localZkS.close();
    }

    @Test
    void testZKCreationRW() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + LOCAL_ZOOKEEPER_PORT, SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);
        localZkc.close();
    }

    @Test
    void testZKCreationRO() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + LOCAL_ZOOKEEPER_PORT,
                SessionType.AllowReadOnly, (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        localZkc.close();
    }

    @Test
    void testZKCreationFailure() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("invalid", SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        assertTrue(zkFuture.isCompletedExceptionally());
    }
}