Creates the database if not exist.

@param drop
the drop
@throws URISyntaxException
the URI syntax exception
@throws IOException
Signals that an I/O exception has occurred.
@throws ClientProtocolException
the client protocol exception
423828
private void createDatabaseIfNotExist(boolean drop) throws URISyntaxException, IOException, ClientProtocolException
    {
        boolean exist = checkForDBExistence();

        if (exist && drop)
        {
            dropDatabase();
            exist = false;
        }
        if (!exist)
        {
            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);

            HttpPut put = new HttpPut(uri);
            HttpResponse putRes = null;
            try
            {
                // creating database.
                putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
            }
            finally
            {
                CouchDBUtils.closeContent(putRes);
            }
        }
    }
226852
@JsonIgnore
  @Override
  public void setUri(URI uri) throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException
  {
    super.setUri(uri);
  }
404026
@Override
    @InterfaceAudience.Private
    protected void maybeCreateRemoteDB() {
        if (!createTarget) {
            return;
        }
        creatingTarget = true;
        Log.v(TAG, "Remote db might not exist; creating it...");

        Future future = sendAsyncRequest("PUT", "", null, new RemoteRequestCompletion() {

            @Override
            public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
                creatingTarget = false;
                if (e != null && e instanceof RemoteRequestResponseException &&
                        ((RemoteRequestResponseException) e).getCode() != 412) {
                    Log.e(TAG, this + ": Failed to create remote db", e);
                    setError(e);
                    triggerStopGraceful();  // this is fatal: no db to push to!
                } else {
                    Log.v(TAG, "%s: Created remote db", this);
                    createTarget = false;
                    beginReplicating();
                }
            }

        });
        pendingFutures.add(future);
    }
756036
@Override
    public ConfigurableRequest createRequest(
            @Nonnull final URI uri,
            @Nonnull final HttpMethod httpMethod) throws IOException {
        HttpRequestBase httpRequest = (HttpRequestBase) createHttpUriRequest(httpMethod, uri);
        return new Request(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));
    }
434750
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
		ClientHttpRequest request = getRequestFactory().createRequest(url, method);
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "Created " + method.name() + " request for \"" + url + "\"");
		}
		return request;
	}
1226917
public void execute(final TSDB tsdb, HttpQuery query) throws IOException {
    final HttpMethod method = query.getAPIMethod();
    
    final String[] uri = query.explodeAPIPath();
    final String endpoint = uri.length > 1 ? uri[1] : "";
    if (endpoint != null && endpoint.toLowerCase().endsWith("bulk")) {
      executeBulk(tsdb, method, query);
      return;
    }
    
    final Annotation note;
    if (query.hasContent()) {
      note = query.serializer().parseAnnotationV1();
    } else {
      note = parseQS(query);
    }
    
    // GET
    if (method == HttpMethod.GET) {
      try {
        if ("annotations".toLowerCase().equals(uri[0])) {
          fetchMultipleAnnotations(tsdb, note, query);
        } else {
          fetchSingleAnnotation(tsdb, note, query);
        }
      } catch (BadRequestException e) {
        throw e;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // POST
    } else if (method == HttpMethod.POST || method == HttpMethod.PUT) {
      
      /**
       * Storage callback used to determine if the storage call was successful
       * or not. Also returns the updated object from storage.
       */
      class SyncCB implements Callback<Deferred<Annotation>, Boolean> {
        
        @Override
        public Deferred<Annotation> call(Boolean success) throws Exception {
          if (!success) {
            throw new BadRequestException(
                HttpResponseStatus.INTERNAL_SERVER_ERROR,
                "Failed to save the Annotation to storage", 
                "This may be caused by another process modifying storage data");
          }
          
          return Annotation.getAnnotation(tsdb, note.getTSUID(), 
              note.getStartTime());
        }
        
      }
      
      try {
        final Deferred<Annotation> process_meta = note.syncToStorage(tsdb, 
            method == HttpMethod.PUT).addCallbackDeferring(new SyncCB());
        final Annotation updated_meta = process_meta.joinUninterruptibly();
        tsdb.indexAnnotation(note);
        query.sendReply(query.serializer().formatAnnotationV1(updated_meta));
      } catch (IllegalStateException e) {
        query.sendStatusOnly(HttpResponseStatus.NOT_MODIFIED);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // DELETE    
    } else if (method == HttpMethod.DELETE) {

      try {
        note.delete(tsdb).joinUninterruptibly();
        tsdb.deleteAnnotation(note);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException(
            "Unable to delete Annotation information", e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      query.sendStatusOnly(HttpResponseStatus.NO_CONTENT);
      
    } else {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
          "Method not allowed", "The HTTP method [" + method.getName() +
          "] is not permitted for this endpoint");
    }
  }
343012
protected void createTable(TableName tableName, CreateTableRequest request)
          throws IOException {
    try {
      tableAdminClientWrapper.createTable(request);
    } catch (Throwable throwable) {
      throw convertToTableExistsException(tableName, throwable);
    }
  }
1245551
protected void dropDatabase(String database)
  {

    log.debug("dropping possible existing database");
    closeAllConnections(database);
    getJdbcTemplate().execute("DROP DATABASE IF EXISTS " + database);

  }
56990
private IJdbcClient createClient(IPolicyContext context, JDBCIdentitySource config) throws Throwable {
        IJdbcComponent jdbcComponent = context.getComponent(IJdbcComponent.class);

        if (config.getType() == JDBCType.datasource || config.getType() == null) {
            DataSource ds = lookupDatasource(config);
            return jdbcComponent.create(ds);
        }
        if (config.getType() == JDBCType.url) {
            JdbcOptionsBean options = new JdbcOptionsBean();
            options.setJdbcUrl(config.getJdbcUrl());
            options.setUsername(config.getUsername());
            options.setPassword(config.getPassword());
            options.setAutoCommit(true);
            return jdbcComponent.createStandalone(options);
        }
        throw new Exception("Unknown JDBC options."); //$NON-NLS-1$
    }
462303
@Override
    public Delete createDelete(URI id, String tableName) throws IOException {
        Delete del = null;
        HTable hTable = getTable(tableName);
        if (hTable != null) {
            del = new Delete(Bytes.toBytes(id.toString()));
        }
        return del;
    }
1370422
public void store() throws IOException
    {
        try {
            File file = new File(url.toURI());
            storeAs(file);
        }
        catch (URISyntaxException ex)
        {
            throw new RuntimeException(ex);
        }
    }
1221297
public static void main(final String... args) {
		((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql")).setLevel(Level.DEBUG);
		((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.client")).setLevel(Level.ERROR);
		((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.context")).setLevel(Level.ERROR);
		((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.store")).setLevel(Level.ERROR);

		String propFile = "repl.properties";
		if (args.length != 0) {
			propFile = args[0];
		}

		Path path = Paths.get(propFile);

		if (!Files.exists(path)) {
			throw new IllegalArgumentException("properties could not found.");
		}

		try {
			SqlREPL repl = new SqlREPL(path);
			repl.execute();
		} catch (Exception ex) {
			throw new IllegalStateException("Failed to REPL.", ex);
		}
	}
490536
@Override
    public void dropSchema()
    {
        try
        {
            if (operation != null && ("create-drop").equalsIgnoreCase(operation))
            {
                r.dbDrop(databaseName);
            }
        }
        catch (Exception e)
        {
            logger.error("Error while dropping schema", e);
            throw new SchemaGenerationException(e, "RethinkDB");
        }
    }
628709
public static void createTables(Connection connection) throws Exception {
        StringBuilder sB = new StringBuilder();
        sB.append("CREATE TABLE ");
        sB.append(TABLE_METADATA);
        sB.append(" (");
        sB.append(MetadataTableFields.COLUMN_KEY.getFieldName()).append(" TEXT NOT NULL, ");
        sB.append(MetadataTableFields.COLUMN_VALUE.getFieldName()).append(" TEXT NOT NULL ");
        sB.append(");");
        String CREATE_TABLE_PROJECT = sB.toString();

        try (Statement statement = connection.createStatement()) {
            statement.setQueryTimeout(30); // set timeout to 30 sec.

            statement.executeUpdate(CREATE_TABLE_PROJECT);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage());
        }
    }
1269617
public boolean create() throws DBException
    {
        boolean bSuccess = true;
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        ResultSet resultSet = (ResultSet)this.getResultSet();
        if (resultSet == null)
        {
            Map<String,Object> properties = this.getDatabase().getProperties();
            String strAltSecondaryIndex = (String)this.getDatabase().getProperties().get(SQLParams.ALT_SECONDARY_INDEX);
            try   {
                int iFirstIndex = 0;
                Record record = this.getRecord();
                StringBuilder sql = new StringBuilder();
                sql.append("CREATE TABLE ");
                sql.append(record.makeTableNames(true));
                sql.append(" (");
                for (int iIndex = 0; iIndex < record.getFieldCount(); iIndex++)
                {
                    BaseField field = record.getField(iIndex);
                    if (field.isVirtual())
                        continue;
                    String strType = field.getSQLType(true, properties);
                    if (field instanceof CounterField)
                        if (this.getDatabase().isAutosequenceSupport())
                        {
                            String strCounterType = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_TYPE);
                            if (strCounterType != null)
                                strType = strCounterType;
                            String strAutoseqExtra = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_EXTRA);
                            if (strAutoseqExtra != null)
                                strType += strAutoseqExtra;
                            String strCounterExtra = (String)this.getDatabase().getProperties().get(SQLParams.COUNTER_EXTRA);
                            if (strCounterExtra != null)
                            {
                                strType += strCounterExtra;
                                iFirstIndex = 1;    // No need to build primary index
                            }
                        }
                    if (iIndex > 0)
                        sql.append(", ");
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_KEY_SUPPORT)))
                        this.checkNullableKey(field, strAltSecondaryIndex != null); // Set the key to not nullable for create.
                    if (!field.isNullable())
                    	if (!DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		strType += " NOT NULL";
                    if (strAltSecondaryIndex != null)
                        if (this.checkIndexField(field))
                            strType += ' ' + strAltSecondaryIndex;
                    sql.append(field.getFieldName(true, false)).append(' ').append(strType);
                }
                String strPrimaryKey = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_PRIMARY_KEY);
                if (strPrimaryKey != null)
                    if (record.getCounterField() != null)
                        if (this.getDatabase().isAutosequenceSupport())
                {
                    sql.append(", ").append(strPrimaryKey).append(" (").append(record.getCounterField().getFieldName(true, false)).append(")");
                    iFirstIndex = 1;    // No need to build primary index
                }
                sql.append(")");
                Utility.getLogger().info(sql.toString());
                if (DBConstants.TRUE.equals((String)this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
                if (this.getStatement(DBConstants.SQL_CREATE_TYPE) == null)
                    this.setStatement(((JdbcDatabase)this.getDatabase()).getJDBCConnection().createStatement(), DBConstants.SQL_CREATE_TYPE);
                this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                // Now set up the index(es)
                sql = new StringBuilder();
                String strPrimaryKeySQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_PRIMARY_INDEX);
                if (strPrimaryKeySQL == null)   // null=use default, If empty string, not supported.
                    strPrimaryKeySQL = "CREATE ${unique} INDEX ${keyname} ON ${table} (${fieldsandorder})";    // Default
                String strCreateIndexSQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_INDEX);
                if (strCreateIndexSQL == null)   // null=use default, If empty string, not supported.
                    strCreateIndexSQL = strPrimaryKeySQL;    // Default
                for (int iIndex = iFirstIndex; iIndex < record.getKeyAreaCount(); iIndex++)
                {
                    KeyArea keyArea = record.getKeyArea(iIndex);
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE)
                        && (iIndex == iFirstIndex)
                            && (keyArea.getKeyFields() == 1))
                        sql = new StringBuilder(strPrimaryKeySQL);
                    else
                        sql = new StringBuilder(strCreateIndexSQL);
                    if (sql.length() == 0)
                        continue;   // Not supported.
                    boolean indexCanBeUnique = true;
                	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_UNIQUE_KEYS)))
                        if (iIndex > 0)
                    {	// This db considers null a valid index value and will throw a unique key error on write
                        for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                        {
                            KeyField keyField = keyArea.getKeyField(iFieldIndex);
                            BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                            if (field.isNullable())
                            	indexCanBeUnique = false;
                        }
                    }
                    if (iIndex > 0)
                    	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		indexCanBeUnique = false;
                    
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE) && (indexCanBeUnique))
                        sql = Utility.replace(sql, "${unique}", "UNIQUE");
                    else
                        sql = Utility.replace(sql, "${unique}", DBConstants.BLANK);
                    String strKeyName = keyArea.getKeyName();
                    String strTableNames = record.makeTableNames(true);
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_DUPLICATE_KEY_NAMES)))
                    {
                    	if (strTableNames.endsWith("_temp"))
                    		strKeyName = strTableNames.substring(0, strTableNames.length() - 5) + "_" + strKeyName;
                    	else
                    		strKeyName = strTableNames + "_" + strKeyName;
                    }
                    String strMaxKeyNameLength = (String)this.getDatabase().getProperties().get(SQLParams.MAX_KEY_NAME_LENGTH);
                    if (strMaxKeyNameLength != null)
                    {
                        int iMaxKeyNameLength = Integer.parseInt(strMaxKeyNameLength);
                        if (strKeyName.length() > iMaxKeyNameLength)
                        {
                        	strKeyName = strKeyName + (int)(Math.random() * 100000);
                            strKeyName = strKeyName.substring(strKeyName.length() - iMaxKeyNameLength);
                            while (!Character.isLetter(strKeyName.charAt(0))) {
                            	strKeyName = strKeyName.substring(1);
                            }
                        }
                    }
                    sql = Utility.replace(sql, "${keyname}", strKeyName);
                    sql = Utility.replace(sql, "${table}", strTableNames);
                    String strFields = DBConstants.BLANK;
                    String strFieldAndOrder = DBConstants.BLANK;
                    for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                    {
                        KeyField keyField = keyArea.getKeyField(iFieldIndex);
                        BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                        if (iFieldIndex > 0)
                        {
                            strFields += ", ";
                            strFieldAndOrder += ", ";
                        }
                        strFields += field.getFieldName(true, false) + " ";
                        strFieldAndOrder += field.getFieldName(true, false) + " ";
                        if (keyField.getKeyOrder() == DBConstants.DESCENDING)
                            strFieldAndOrder += "DESC ";
                    }
                    sql = Utility.replace(sql, "${fields}", strFields);
                    sql = Utility.replace(sql, "${fieldsandorder}", strFieldAndOrder);
                    Utility.getLogger().info(sql.toString());
                    this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                }
            } catch (SQLException e)    {
                throw this.getDatabase().convertError(e);
            } finally {
                if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
            }
        }
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        return bSuccess;    // Success!!!
    }
645154
public static void writeReadDeleteDocument(DatabaseClient client, String filename, String format) throws IOException {
    // create a manager for documents of any format
    GenericDocumentManager docMgr = client.newDocumentManager();

    InputStream docStream = Util.openStream("data"+File.separator+filename);
    if (docStream == null)
      throw new IOException("Could not read document example");

    // create an identifier for the document
    String docId = "/example/"+filename;

    // create a handle for the document
    InputStreamHandle writeHandle = new InputStreamHandle();
    writeHandle.set(docStream);

    // write the document
    docMgr.write(docId, writeHandle);

    // create a handle to receive the document content
    BytesHandle readHandle = new BytesHandle();

    // read the document content
    docMgr.read(docId, readHandle);

    // access the document content
    byte[] document = readHandle.get();

    // ... do something with the document content ...

    // delete the document
    docMgr.delete(docId);

    System.out.println("Wrote, read, and deleted /example/"+filename+
      " content with "+document.length+" bytes in the "+format+" format");
  }
24155
public <T extends Parameter> T copy() throws URISyntaxException {
        if (factory == null) {
            throw new UnsupportedOperationException("No factory specified");
        }
        return (T) factory.createParameter(getValue());
    }