Get all backup data

@param model
@return
@throws Exception
559148
@SuppressWarnings("deprecation")
    @RequestMapping(value = "/api/backup", method = RequestMethod.GET)
    public
    @ResponseBody
    String getBackup(Model model, HttpServletResponse response) throws Exception {
        response.addHeader("Content-Disposition", "attachment; filename=backup.json");
        response.setContentType("application/json");

        Backup backup = BackupService.getInstance().getBackupData();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();

        return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);
    }
1330299
@RequestMapping(value = "/api/backup", method = RequestMethod.POST)
    public
    @ResponseBody
    Backup processBackup(@RequestParam("fileData") MultipartFile fileData) throws Exception {
        // Method taken from: http://spring.io/guides/gs/uploading-files/
        if (!fileData.isEmpty()) {
            try {
                byte[] bytes = fileData.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File("backup-uploaded.json")));
                stream.write(bytes);
                stream.close();

            } catch (Exception e) {
            }
        }
        File f = new File("backup-uploaded.json");
        BackupService.getInstance().restoreBackupData(new FileInputStream(f));
        return BackupService.getInstance().getBackupData();
    }
310649
def _count_model(self, model):
        
        try:
            res = model.objects.all().count()
        except Exception as e:
            self.err(e)
            return
        return res
1317276
public List<BackupMetaData> getAvailableBackups() throws Exception
    {
        Map<String, String> config = getBackupConfig();
        return backupProvider.get().getAvailableBackups(exhibitor, config);
    }
751405
public function tryLoadAny(Model $m)
    {
        if (!$this->mode) {
            $this->mode = 'r';
        } elseif ($this->mode == 'w') {
            throw new Exception(['Currently writing records, so loading is not possible.']);
        }

        if (!$this->handle) {
            $this->loadHeader();
        }

        $data = $this->getLine();
        if (!$data) {
            return;
        }

        $data = $this->typecastLoadRow($m, $data);
        $data['id'] = $this->line;

        return $data;
    }
199204
@RequestMapping(value = "api/servergroup", method = RequestMethod.GET)
    public
    @ResponseBody
    HashMap<String, Object> getServerGroups(Model model,
                                            @RequestParam(value = "profileId", required = false) Integer profileId,
                                            @RequestParam(value = "search", required = false) String search,
                                            @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier) throws Exception {
        if (profileId == null && profileIdentifier == null) {
            throw new Exception("profileId required");
        }
        if (profileId == null) {
            profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);
        }

        List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);

        if (search != null) {
            Iterator<ServerGroup> iterator = serverGroups.iterator();
            while (iterator.hasNext()) {
                ServerGroup serverGroup = iterator.next();
                if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {
                    iterator.remove();
                }
            }
        }
        HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, "servergroups");
        return returnJson;
    }
1091174
private SnapshotInfo getRestorePlan() throws Exception {
        // Wait for ZK to publish the snapshot fragment/info structures.
        List<String> children = waitOnVoltZK_restore();

        // If not recovering, nothing to do.
        if (m_action.doesRequireEmptyDirectories()) {
            return null;
        }

        Map<String, Set<SnapshotInfo>> snapshotFragments = new HashMap<String, Set<SnapshotInfo>>();
        Long clStartTxnId = deserializeRestoreInformation(children, snapshotFragments);

        // If command log has no snapshot requirement clear the fragment set directly
        if (clStartTxnId != null && clStartTxnId == Long.MIN_VALUE) {
            snapshotFragments.clear();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("There are " + snapshotFragments.size() + " restore candidate snapshots available in the cluster");
        }

        // Find the last complete snapshot and use it
        HashMap<String, Map<String, Set<Integer>>> snapshotTablePartitions =
            new HashMap<String, Map<String,Set<Integer>>>();
        Iterator<Entry<String, Set<SnapshotInfo>>> it = snapshotFragments.entrySet().iterator();
        SnapshotInfo newest = null;
        while (it.hasNext()) {
            Entry<String, Set<SnapshotInfo>> e = it.next();
            Set<String> fileTables = new HashSet<String>();
            Set<String> digestTables = null;
            String nonce = e.getKey();
            Map<String, Set<Integer>> tablePartitions = snapshotTablePartitions.get(nonce);
            if (tablePartitions == null) {
                tablePartitions = new HashMap<String, Set<Integer>>();
                snapshotTablePartitions.put(nonce, tablePartitions);
            }

            int totalPartitions = -1;
            boolean inconsistent = false;
            Set<SnapshotInfo> fragments = e.getValue();
            for (SnapshotInfo s : fragments) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("SnapshotInfo " + s.nonce + " claims digest tables: " + s.digestTables);
                    LOG.debug("SnapshotInfo " + s.nonce + " claims files for tables: " + s.fileTables);
                }
                if (digestTables == null) {
                    digestTables = new HashSet<String>(s.digestTables);
                }
                else if (!digestTables.equals(s.digestTables)) {
                    m_snapshotErrLogStr.append("\nRejected snapshot ")
                                    .append(s.nonce)
                                    .append(" due to disagreement in digest table list.  Got ")
                                    .append(s.digestTables)
                                    .append(", expecting ")
                                    .append(digestTables);
                    inconsistent = true;
                    break;
                }
                fileTables.addAll(s.fileTables);
                if (totalPartitions == -1) {
                    totalPartitions = s.partitionCount;
                } else if (totalPartitions != s.partitionCount) {
                    m_snapshotErrLogStr.append("\nRejected snapshot ")
                                    .append(s.nonce)
                                    .append(" due to partition count mismatch. Got ")
                                    .append(s.partitionCount)
                                    .append(", expecting ")
                                    .append(totalPartitions);
                    inconsistent = true;
                    break;
                }

                for (Entry<String, Set<Integer>> entry : s.partitions.entrySet()) {
                    Set<Integer> partitions = tablePartitions.get(entry.getKey());
                    if (partitions == null) {
                        tablePartitions.put(entry.getKey(), entry.getValue());
                    } else {
                        partitions.addAll(entry.getValue());
                    }
                }

                if (inconsistent) {
                    break;
                }
            }

            // Check that we have files for all the tables listed in the digest
            if (!fileTables.equals(digestTables)) {
                m_snapshotErrLogStr.append("\nRejected snapshot ")
                    .append(nonce)
                    .append(" because there were not table files for all tables in the digest.  Expected ")
                    .append(digestTables)
                    .append(", but only found table data for ")
                    .append(fileTables);
                inconsistent = true;
            }

            // Check if we have all the partitions
            for (Set<Integer> partitions : tablePartitions.values()) {
                if (partitions.size() != totalPartitions) {
                    m_snapshotErrLogStr.append("\nRejected snapshot ")
                                    .append(nonce)
                                    .append(" due to missing partitions. Got ")
                                    .append(partitions.size())
                                    .append(", expecting ")
                                    .append(totalPartitions);
                    inconsistent = true;
                }
            }

            if (inconsistent) {
                it.remove();
            }
            else {
                SnapshotInfo current = consolidateSnapshotInfos(fragments);
                if (newest == null || current.isNewerThan(newest)) {
                    newest = current;
                }
            }
        }

        // If we have a command log and it requires a snapshot but no snapshot
        // fragments were found, simply bail (or, if we didn't find a viable
        // snapshot from which to recover)
        // Reluctant to muck with the first predicate here, even though
        // the newest == null should cover all of the 'no viable snapshot' possiblities
        if ((clStartTxnId != null && clStartTxnId != Long.MIN_VALUE &&
            snapshotFragments.size() == 0) || newest == null) {
            if (m_snapshotErrLogStr.length() > 0) {
                LOG.error(m_snapshotErrLogStr.toString());
            }
            throw new RuntimeException("No viable snapshots to restore");
        }

        if (snapshotFragments.isEmpty()) {
            return null;
        } else {
            return newest;
        }
    }
859714
protected void doBackup(File backupFile) throws BackupException
   {
      ZipObjectWriter out = null;
      try
      {
         out = new ZipObjectWriter(PrivilegedFileHelper.zipOutputStream(backupFile));
         quotaPersister.backupWorkspaceData(rName, wsName, out);
      }
      catch (IOException e)
      {
         throw new BackupException(e);
      }
      finally
      {
         if (out != null)
         {
            try
            {
               out.close();
            }
            catch (IOException e)
            {
               LOG.error("Can't close output stream", e);
            }
         }
      }
   }
1288562
public Map getModelEntryMap(Map requestParamMap,String tableName,String modelName,String dbName) throws Exception{
		return getModelEntryMap( requestParamMap, tableName, modelName, dbName,"");
	}
1263613
protected void save(Model model, String filename) {
        try {
            ModelSerializer.writeModel(model, filename, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
762640
@Override
	public RocksDBRestoreResult restore() throws Exception {

		if (restoreStateHandles == null || restoreStateHandles.isEmpty()) {
			return null;
		}

		final KeyedStateHandle theFirstStateHandle = restoreStateHandles.iterator().next();

		boolean isRescaling = (restoreStateHandles.size() > 1 ||
			!Objects.equals(theFirstStateHandle.getKeyGroupRange(), keyGroupRange));

		if (isRescaling) {
			restoreWithRescaling(restoreStateHandles);
		} else {
			restoreWithoutRescaling(theFirstStateHandle);
		}
		return new RocksDBRestoreResult(this.db, defaultColumnFamilyHandle,
			nativeMetricMonitor, lastCompletedCheckpointId, backendUID, restoredSstFiles);
	}
1053399
def fetch_all_backups(self):
        
        """
        api = self.doapi_manager
        for obj in api.paginate(self.url + '/backups', 'backups'):
            yield Image(obj, doapi_manager=api)
1245463
public function actionModel($model = null)
    {
        if (!$model) {
            $model = $this->prompt('Namespaced path to the ngrest model (e.g. "app\models\Users"):');
        }
        $object = Yii::createObject(['class' => $model]);
        
        if (!$object instanceof NgRestModelInterface) {
            throw new Exception("Model must be instance of NgRestModelInterface.");
        }
        
        $reflector = new \ReflectionClass($model);
        $fileName = $reflector->getFileName();
        $path = dirname($fileName);
        $apiEndpoint = $object->ngrestApiEndpoint();
        $i18n = !empty($object->i18n);
        $data = [
            'path' =>  $path,
            'fileName' => basename($fileName),
            'content' => $this->generateModelContent(
                $reflector->getNamespaceName(),
                $reflector->getShortName(),
                $apiEndpoint,
                Yii::$app->db->getTableSchema($object->tableName(), true),
                $i18n
             ),
        ];
        
        $this->generateFile($data);
    }
1013080
def get(self, storagemodel) -> StorageTableModel:
        

        modeldefinition = self.getmodeldefinition(storagemodel, True)

        try:

            pk = storagemodel.getPartitionKey()
            rk = storagemodel.getRowKey()

            entity = modeldefinition['tableservice'].get_entity(modeldefinition['tablename'], pk, rk)
            storagemodel._exists = True
        
            """ sync with entity values """
            for key, default in vars(storagemodel).items():
                if not key.startswith('_') and key not in ['','PartitionKey','RowKey']:
                    value = getattr(entity, key, None)
                    if not value is None:
                        setattr(storagemodel, key, value)
             
        except AzureMissingResourceHttpError as e:
            log.debug('can not get table entity:  Table {}, PartitionKey {}, RowKey {} because {!s}'.format(modeldefinition['tablename'], pk, rk, e))
            storagemodel._exists = False

        except Exception as e:
            msg = 'can not get table entity:  Table {}, PartitionKey {}, RowKey {} because {!s}'.format(modeldefinition['tablename'], pk, rk, e)
            raise AzureStorageWrapException(msg=msg)

        finally:
            return storagemodel
533961
protected Map<String, Object> getModelAttributes(final Map<String, Object> model) {
        return (Map<String, Object>) model.get(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES);
    }
1154442
public void start() throws Exception
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED));

        //Try to restore data from backup before zookeeper will be started
        backupManager.restoreAll();

        activityQueue.start();
        configManager.start();
        monitorRunningInstance.start();
        cleanupManager.start();
        backupManager.start();
        autoInstanceManagement.start();
        if ( servoMonitoring != null )
        {
            servoMonitoring.start();
        }

        configManager.addConfigListener
        (
            new ConfigListener()
            {
                @Override
                public void configUpdated()
                {
                    try
                    {
                        resetLocalConnection();
                    }
                    catch ( IOException e )
                    {
                        log.add(ActivityLog.Type.ERROR, "Resetting connection", e);
                    }
                }
            }
        );
    }
1007074
public static backup_file delete(nitro_service client, backup_file resource) throws Exception
	{
		resource.validate("delete");
		return ((backup_file[]) resource.delete_resource(client))[0];
	}