001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.wsclient.system.internal;
021
022import org.json.simple.JSONValue;
023import org.sonar.wsclient.internal.HttpRequestFactory;
024import org.sonar.wsclient.system.Migration;
025import org.sonar.wsclient.system.SystemClient;
026
027import java.util.Collections;
028import java.util.Map;
029
030public class DefaultSystemClient implements SystemClient {
031
032  private final HttpRequestFactory requestFactory;
033
034  public DefaultSystemClient(HttpRequestFactory requestFactory) {
035    this.requestFactory = requestFactory;
036  }
037
038  @Override
039  public Migration migrate() {
040    String json = requestFactory.post("/api/server/setup", Collections.<String, Object>emptyMap());
041    return jsonToMigration(json);
042  }
043
044  @Override
045  public Migration migrate(long timeoutInMs, long rateInMs) {
046    if (rateInMs >= timeoutInMs) {
047      throw new IllegalArgumentException("Timeout must be greater than rate");
048    }
049    Migration migration = null;
050    boolean running = true;
051    long endAt = System.currentTimeMillis() + timeoutInMs;
052    while (running && System.currentTimeMillis() < endAt) {
053      migration = migrate();
054      if (migration.status() == Migration.Status.MIGRATION_NEEDED ||
055        migration.status() == Migration.Status.MIGRATION_RUNNING) {
056        sleepQuietly(rateInMs);
057      } else {
058        running = false;
059      }
060    }
061    return migration;
062  }
063
064  @Override
065  public void restart() {
066    requestFactory.post("/api/system/restart", Collections.<String, Object>emptyMap());
067  }
068
069  private void sleepQuietly(long rateInMs) {
070    try {
071      Thread.sleep(rateInMs);
072    } catch (InterruptedException e) {
073      throw new IllegalStateException("Fail to sleep!", e);
074    }
075  }
076
077  private Migration jsonToMigration(String json) {
078    Map jsonRoot = (Map) JSONValue.parse(json);
079    return new DefaultMigration(jsonRoot);
080  }
081}