bimface 模型集成-后端(java)上传、发起转换、获取转换状态

前言

之前没有注意官方有个sdk,然后自己就实现了这么个逻辑。建议直接用官方的sdk来嵌入自己的项目。

后端架构

springboot(jeecgboot) + mybatisplus

流程

存储表结构

  • sys_beamface_accesstoken 存储accesstoken. (上传、发起转换、获取转换状态\获取viewtoken 时需要用到accesstoken,)
  • sys_beamface_model_viewtoken 存储viewtoken(流程模型或图纸需要用到)
  • dt_doc中的 bim_file_id 存储模型/图纸上传到bimface后返回的bimface文件ID,
    status 0表示文件未处理,1表示文件已上传,2表示文件已发起转换,3表示文件转换成功
    在这里插入图片描述
    在这里插入图片描述

全局工具类

package org.jeecg.business.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

/**
 * HTTP工具类 单例模式
 *
 */
public class HttpClientUtil {
	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
	private static PoolingHttpClientConnectionManager cm;
	private static String EMPTY_STR = null;
	private static String UTF_8 = "utf-8";

	private static void init() {
		if (cm == null) {
			cm = new PoolingHttpClientConnectionManager();
			cm.setMaxTotal(1000);// 整个连接池最大连接数
			cm.setDefaultMaxPerRoute(500);// 每路由最大连接数
		}
	}

	/**
	 * 通过连接池获取HttpClient
	 * 
	 * @return
	 */
	private static CloseableHttpClient getHttpClient() {
		init();
		return HttpClients.custom().setConnectionManager(cm).build();
	}

	/**
	 * Get请求 不带参数
	 * 
	 * @param url
	 * @return
	 */
	public static String httpGetRequest(String url) {
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(setTimedOut());
		return getResult(httpGet);
	}

	/**
	 * Get请求 带参数
	 * 
	 * @param url
	 * @param params map
	 * @return
	 * @throws URISyntaxException
	 */
	public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);

		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		ub.setParameters(pairs);

		HttpGet httpGet = new HttpGet(ub.build());
		httpGet.setConfig(setTimedOut());
		return getResult(httpGet);
	}

	/**
	 * Get请求 带头域与带参数
	 * 
	 * @param url
	 * @param headers 页面头域
	 * @param params  map
	 * @return
	 * @throws URISyntaxException
	 */
	public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
			throws URISyntaxException {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);

		if (!ObjectUtils.isEmpty(params)) {
			ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
			ub.setParameters(pairs);
		}

		HttpGet httpGet = new HttpGet(ub.build());
		httpGet.setConfig(setTimedOut());

		for (Map.Entry<String, Object> param : headers.entrySet()) {
			httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
		}

		return getResult(httpGet);
	}

	/**
	 * Post请求 不带参数
	 * 
	 * @param url
	 * @return
	 */
	public static String httpPostRequest(String url) {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());
		return getResult(httpPost);
	}

	/**
	 * Post请求 带参数
	 * 
	 * @param url
	 * @param params map
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());

		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
		return getResult(httpPost);
	}

	/**
	 * Post请求 带头域与带参数
	 * 
	 * @param url
	 * @param headers 头域
	 * @param params  map
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
			throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());

		for (Map.Entry<String, Object> param : headers.entrySet()) {
			httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
		}

		if (!ObjectUtils.isEmpty(params)) {
			ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
			httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
		}
		return getResult(httpPost);
	}
	
	public static String httpPutRequestByRb(String url,  Map<String, Object> headers, String josnString) throws UnsupportedEncodingException {
		HttpPut httpPut = new HttpPut(url);
		httpPut.setConfig(setTimedOut());
		httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
		httpPut.setHeader("Date", new Date() + "");
		httpPut.setHeader("Accept", "application/json");
		httpPut.setHeader("Cache-Control", "no-store");
		for (Map.Entry<String, Object> param : headers.entrySet()) {
			httpPut.addHeader(param.getKey(), String.valueOf(param.getValue()));
		}
		StringEntity s = new StringEntity(josnString);
		s.setContentEncoding(UTF_8);
		s.setContentType("application/json");// 发送json数据需要设置contentType
		httpPut.setEntity(s);
		return getResult(httpPut);
	}
	

	public static String postFileMultiPart(String url, Map<String, ContentBody> params, String fileParamName) {
		HttpPost httpPost = new HttpPost(url);
		RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
		httpPost.setConfig(defaultRequestConfig);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		for (Entry<String, ContentBody> entry : params.entrySet()) {
			if (fileParamName.equals(entry.getKey())) continue;
			builder.addPart(entry.getKey(), entry.getValue());
		}
		builder.addPart(fileParamName, params.get(fileParamName));
		HttpEntity reqEntity = builder.build();
		httpPost.setEntity(reqEntity);
		
		return getResult(httpPost);
	}

	/**
	 * map 处理方法
	 * 
	 * @param params
	 * @return
	 */
	private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
		}
		return pairs;
	}

	/**
	 * POST请求 带json格式的字符串参数
	 * 
	 * @param url
	 * @param json json格式的字符串
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostRequest(String url, String josnString) throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());
		StringEntity s = new StringEntity(josnString);
		s.setContentEncoding(UTF_8);
		s.setContentType("application/json");// 发送json数据需要设置contentType
		httpPost.setEntity(s);
		return getResult(httpPost);
	}

	/**
	 * POST请求 带json格式的字符串参数
	 * 
	 * @param url
	 * @param json json格式的字符串
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostRequest4Urlencoded(String url, String urlencoded) throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());
		StringEntity s = new StringEntity(urlencoded);
		s.setContentEncoding(UTF_8);
		s.setContentType("application/x-www-form-urlencoded");
		httpPost.setEntity(s);
		return getResult(httpPost);
	}

	/**
	 * 使用POSt方式通过Xml发送HTTP请求
	 * 
	 * @param url 请求的URL地址
	 * @param Xml 请求的Xml内容
	 * @return 请求返回的内容体
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostXmlRequest(String url, String xmlBody) throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());
		httpPost.addHeader("content-type", "application/xml");

		StringEntity s = new StringEntity(xmlBody);
		s.setContentEncoding(UTF_8);
		s.setContentType("application/xml");// 设置contentType
		httpPost.setEntity(s);
		return getResult(httpPost);
	}

	/**
	 * 使用PUT方式通过Xml发送HTTP请求
	 * 
	 * @param url 请求的URL地址
	 * @param Xml 请求的Xml内容
	 * @return 请求返回的内容体
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPutXmlRequest(String url, String xmlBody) throws UnsupportedEncodingException {
		HttpPut httpPut = new HttpPut(url);
		httpPut.setConfig(setTimedOut());
		// httpPut.setHeader("Content-Type", "application/xml");
		// httpPut.addHeader("content-type", "application/xml");
		httpPut.setHeader("Content-Type", "application/xml;charset=UTF-8");

		StringEntity s = new StringEntity(xmlBody, Charset.forName("UTF-8"));
		s.setContentEncoding(UTF_8);
		s.setContentType("application/xml");// 设置contentType
		httpPut.setEntity(s);
		return getResult(httpPut);
	}

	/**
	 * 设置Http连接超时间 单位毫秒 setConnectTimeout:设置连接超时时间,单位毫秒
	 * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒
	 * setSocketTimeout:请求获取数据的超时时间,单位毫秒
	 * 
	 * @return
	 */
	public static RequestConfig setTimedOut() {
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50000).setConnectionRequestTimeout(20000)
				.setSocketTimeout(50000).build();
		return requestConfig;
	}

	/**
	 * 红包充值新增 POST请求 带json格式的字符串参数
	 * 
	 * @param url
	 * @param json json格式的字符串
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String httpPostRequestByRb(String url, String josnString) throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(setTimedOut());
		httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost.setHeader("Date", new Date() + "");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Cache-Control", "no-store");

		StringEntity s = new StringEntity(josnString);
		s.setContentEncoding(UTF_8);
		s.setContentType("application/json");// 发送json数据需要设置contentType
		httpPost.setEntity(s);
		return getResult(httpPost);
	}
	
	

	/**
	 * 处理Http请求
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private static String getResult(HttpRequestBase request) {
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		int code = 0;// 状态码
		try {
 			response = httpClient.execute(request);
			code = response.getStatusLine().getStatusCode();
			log.info("{}", response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (code != 200) {
				if (entity != null) {
					// 打印响应内容
					log.info("*****************response*****************");
					log.info("响应结果: " + EntityUtils.toString(entity));
				}
				return EMPTY_STR;
			}
			if (entity != null) {
				return EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			log.error("调用接口异常: " + request, e);
		} finally {
			try {
				response.close();
			} catch (IOException e1) {
				log.error("response关闭异常", e1);
			}
			log.info("状态码[" + code + "]调用接口:" + request);
		}
		return EMPTY_STR;
	}

}

先根据appid, appsecret 生成accesstoken, 保存到自己的存储服务器。

@Value("${beamface.appKey}")
	private String beamfaceAppKey;
	
	@Value("${beamface.appSecret}")
	private String beamfaceAppSecret;
	
	public static final String GET_ACCESS_TOKEN_URL = "https://api.bimface.com/oauth2/token";
// 获取token逻辑
public String getAccesstoken() {
		// 检查当前系统的accesstoken是否过期
		List<SysBeamfaceAccesstoken> accesstokens = list();
		if (CollectionUtils.isEmpty(accesstokens)) {
			SysBeamfaceAccesstoken accesstoken = new SysBeamfaceAccesstoken();
			Map<String, Object> result = getToken();
			accesstoken.setAcessToken(result.get("token").toString());
			try {
				Date date = DateUtils.parseDate(result.get("expireTime").toString(), "yyyy-MM-dd hh:mm:ss");
				// 保留10分钟误差
				long l = DateUtils.getMillis(date) - 600 * 1000;
				accesstoken.setExpiretimets(Long.toString(l));
			} catch (ParseException e) {
				throw new JeecgBootException(e.getMessage());
			}
			save(accesstoken);
			return accesstoken.getAcessToken();
		} else {
			// 判断时间是否过期
			SysBeamfaceAccesstoken accesstoken = accesstokens.get(0);
			long expireDate = DateUtils.getMillis();
			long old = Long.valueOf(accesstoken.getExpiretimets());
			// 没过期
			if (expireDate < old) {
				return accesstoken.getAcessToken();
			} else {
				Map<String, Object> result = getToken();
				accesstoken.setAcessToken(result.get("token").toString());
				try {
					Date date = DateUtils.parseDate(result.get("expireTime").toString(), "yyyy-MM-dd hh:mm:ss");
					// 保留10分钟误差
					long l = DateUtils.getMillis(date) - 600 * 1000;
					accesstoken.setExpiretimets(Long.toString(l));
				} catch (ParseException e) {
					throw new JeecgBootException(e.getMessage());
				}
				updateById(accesstoken);
				return accesstoken.getAcessToken();
			}
		}
	}

	
	// 请求accesstoken
	@SuppressWarnings("unchecked")
	public Map<String, Object> getToken() {
		if (StringUtils.isEmpty(beamfaceAppKey) || StringUtils.isEmpty(beamfaceAppSecret)) {
			logger.info("未配置beamface.appKey 或者  beamface.appSecret");
			return null;
		}
		// 将字符串 appKey:appSecret 拼接后(中间用冒号连接),对其进行BASE64编码, 然后在编码后的字符串前添加字符串Basic和一个空格, 即:“Basic” + “ ” + Base64Encode(appKey + “:” + appSecret)
		String key = this.beamfaceAppKey + ":" + this.beamfaceAppSecret;
		String authorization = String.format("%s %s", "Basic", Base64Utils.encodeToString(key.getBytes()));
		Map<String, Object> headers = new HashMap<>();
		headers.put("Authorization", authorization);
		try {
			String result = HttpClientUtil.httpPostRequest(GET_ACCESS_TOKEN_URL, headers, null);
			Map<String, Object> map = (Map<String, Object>) JSONUtils.parse(result);
			logger.info("{}", map);
			String success = (String) map.get("code");
			if (!"success".equals(success)) {
				logger.info("请求token失败");
				throw new JeecgBootException("请求access token失败");
			} else {
				return (Map<String, Object>) map.get("data");
			}
		} catch (UnsupportedEncodingException e) {
			throw new JeecgBootException(e.getMessage());
		}
	}

利用保存的 accesstoken 上传模型

思路: 利用保存的 accesstoken,构件定时任务:根据文件后缀格式,获取系统文件转台为0的模型文件流,进行上传。上传后 更新文件状态为 1,然后记录bimface文件ID。

String GET_POLICY_URL = "https://file.bimface.com/upload/policy";

		IDtDocService docService = SpringContextUtils.getBean(IDtDocService.class);
		Environment evn = SpringContextUtils.getBean(Environment.class);
		String uploadPath = evn.getProperty("jeecg.path.upload");
		// 查询状态为0的文件
		QueryWrapper<DtDoc> queryWrapper = new QueryWrapper<>();
		queryWrapper.and(i -> i.eq("status", 0)
				.and(j -> j.like("doc_name", "%.rvt")
						.or(s -> s.like("doc_name", "%.dwg"))
						.or(s -> s.like("doc_name", "%.rfa"))
						.or(s -> s.like("doc_name", "%.fbx"))
						.or(s -> s.like("doc_name", "%.dxf"))
						.or(s -> s.like("doc_name", "%.skp"))
						.or(s -> s.like("doc_name", "%.ifc"))
						.or(s -> s.like("doc_name", "%.dgn"))
						.or(s -> s.like("doc_name", "%.obj"))
						.or(s -> s.like("doc_name", "%.stl"))
						.or(s -> s.like("doc_name", "%.3ds"))
						.or(s -> s.like("doc_name", "%.dae"))
						.or(s -> s.like("doc_name", "%.ply"))
						.or(s -> s.like("doc_name", "%.igms"))));
		List<DtDoc> docList = docService.list(queryWrapper);
		LOGGER.info("扫描到{}个文件需要上传", docList.size());
		for (DtDoc dtDoc : docList) {
			LOGGER.info("开始处理{}", dtDoc.getDocName());
			String id = UUID.randomUUID().toString().replace("-", "").substring(0, 20);
			String token = beamfaceAccesstokenService.getAccesstoken();
			String docName = null;
			// 根据policy凭证上传文件
			String docUrl = dtDoc.getDocUrl();
			try {
				docName = URLEncoder.encode(dtDoc.getDocName(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.error("编码失败");
				LOGGER.error(e.getMessage(), e);
				continue;
			}
			if (StringUtils.isEmpty(docUrl)) {
				LOGGER.error("{} 文件路径不存在", docName);
				continue;
			}
			String filePath = uploadPath + File.separator + docUrl;
			File wlkxFile = new File(filePath);
			if (!wlkxFile.exists()) {
				LOGGER.error("{} 文件不存在", docName);
				continue;
			}
			// 获取policy
			Map<String, Object> headers = new HashMap<>();
			headers.put("Authorization", String.format("%s %s", "bearer", token));
			Map<String, Object> params = new HashMap<>();
			params.put("name", docName);
			params.put("sourceId", id);
			String policyResult = null;
			try {
				policyResult = HttpClientUtil.httpGetRequest(GET_POLICY_URL, headers, params);
			} catch (URISyntaxException e) {
				LOGGER.error("获取policy失败");
				LOGGER.error(e.getMessage(), e);
				continue;
			}
			if (policyResult == null) {
				LOGGER.error("{}, 获取policy失败", dtDoc.getDocName());
				continue;
			}
			LOGGER.info("{} {}, 获取policy成功", dtDoc.getDocName(), policyResult);
			Map<String, Object> policyResult2 = (Map<String, Object>) JSONUtils.parse(policyResult);
			if ("success".equals(policyResult2.get("code").toString())) {
				Map<String, Object> dataMap = (Map<String, Object>) policyResult2.get("data");
				String policy = dataMap.get("policy").toString();
				String host = dataMap.get("host").toString();
				String objectKey = dataMap.get("objectKey").toString();
				String accessId = dataMap.get("accessId").toString();
				String callbackBody = dataMap.get("callbackBody").toString();
				String signature = dataMap.get("signature").toString();
				Map<String,ContentBody> reqParam = new HashMap<String,ContentBody>();
				reqParam.put("name", new StringBody(docName, ContentType.MULTIPART_FORM_DATA));
				reqParam.put("key", new StringBody(objectKey, ContentType.MULTIPART_FORM_DATA));
				reqParam.put("policy", new StringBody(policy, ContentType.MULTIPART_FORM_DATA));
				reqParam.put("OSSAccessKeyId", new StringBody(accessId, ContentType.MULTIPART_FORM_DATA));
				reqParam.put("callback", new StringBody(callbackBody, ContentType.MULTIPART_FORM_DATA));
				reqParam.put("success_action_status", new StringBody("200", ContentType.MULTIPART_FORM_DATA));
				reqParam.put("signature", new StringBody(signature, ContentType.MULTIPART_FORM_DATA));
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				try {
					FileUtils.copyFile(new File(filePath), output);
				} catch (IOException e) {
					LOGGER.error("读取文件失败");
				}
				reqParam.put("file", new ByteArrayBody(output.toByteArray(), docName));
				String uploadResult = HttpClientUtil.postFileMultiPart(host, reqParam, "file");
				if (uploadResult == null) {
					LOGGER.error("{}, upload失败", dtDoc.getDocName());
					continue;
				}
				Map<String, Object> uploadResult2 = (Map<String, Object>) JSONUtils.parse(uploadResult);
				if ("success".equals(uploadResult2.get("code").toString())) {
					dataMap = (Map<String, Object>) uploadResult2.get("data");
					LOGGER.info("{}, upload成功", dtDoc.getDocName());
					String bimfaceId = dataMap.get("fileId").toString();
					dtDoc.setBimFileId(bimfaceId);
					dtDoc.setStatus(1);
					docService.updateById(dtDoc);
				}
			} else {
				LOGGER.error("上传失败");
				continue;
			}
		}
	
	

发起转换

思路:获取文件状态为1的文件,定时获取文件转台,发起转换成功后更新为2.

String CONVERT_URL = "https://api.bimface.com/translate";

		// 查询状态为1的文件
		QueryWrapper<DtDoc> queryWrapper = new QueryWrapper<>();
		queryWrapper.and(i -> i.eq("status", 1)
				.isNotNull("bim_file_id")
				.and(j -> j.like("doc_name", "%.rvt")
						.or(s -> s.like("doc_name", "%.dwg"))
						.or(s -> s.like("doc_name", "%.fbx"))
						.or(s -> s.like("doc_name", "%.rfa"))
						.or(s -> s.like("doc_name", "%.dxf"))
						.or(s -> s.like("doc_name", "%.skp"))
						.or(s -> s.like("doc_name", "%.ifc"))
						.or(s -> s.like("doc_name", "%.dgn"))
						.or(s -> s.like("doc_name", "%.obj"))
						.or(s -> s.like("doc_name", "%.stl"))
						.or(s -> s.like("doc_name", "%.3ds"))
						.or(s -> s.like("doc_name", "%.dae"))
						.or(s -> s.like("doc_name", "%.ply"))
						.or(s -> s.like("doc_name", "%.igms"))));
		List<DtDoc> docList = docService.list(queryWrapper);
		LOGGER.info("扫描到{}个文件需要解析", docList.size());
		Map<String, Object> headersMap = new HashMap<>();
		headersMap.put("Authorization", String.format("%s %s", "bearer", beamfaceAccesstokenService.getAccesstoken()));
		for (DtDoc dtDoc : docList) {
			LOGGER.info("开始处理{}", dtDoc.getDocName());
			String bimFileId = dtDoc.getBimFileId();
			Map<String, Object> sourceMap = new HashMap<>();
			sourceMap.put("fileId", bimFileId);
			sourceMap.put("compressed", null);
			sourceMap.put("rootName", null);
			JSONObject paramMap = new JSONObject();
			paramMap.put("callback", null);
			paramMap.put("config", null);
			paramMap.put("source", sourceMap);
			try {
				String converResult = HttpClientUtil.httpPutRequestByRb(CONVERT_URL, headersMap, paramMap.toJSONString());
				if (converResult == null) {
					LOGGER.error("调用转换服务失败");
					continue;
				}
				Map<String, Object> converResultJson = (Map<String, Object>) JSONUtils.parse(converResult);
				String code = converResultJson.get("code").toString();
				if ("success".equals(code)) {
					LOGGER.info("调用转换服务成功");
					dtDoc.setStatus(2);
					docService.updateById(dtDoc);
					continue;
				} else {
					LOGGER.error("调用转换服务失败");
					continue;
				}
			} catch (UnsupportedEncodingException e) {
				LOGGER.error("调用转换服务失败");
				LOGGER.error(e.getMessage(), e);
				continue;
			}
		}
	

获取转换状态

思路:定时查询文件状态为2的模型,查询bimface的转换状态,成功后转换为3

String GET_CONVERT_URL = "https://api.bimface.com/translate";

IDtDocService docService = SpringContextUtils.getBean(IDtDocService.class);
		// 查询状态为2的文件
		QueryWrapper<DtDoc> queryWrapper = new QueryWrapper<>();
		queryWrapper.and(i -> i.eq("status", 2).isNotNull("bim_file_id")
				.and(j -> j.like("doc_name", "%.rvt")
				.or(s -> s.like("doc_name", "%.dwg"))
				.or(s -> s.like("doc_name", "%.rfa"))
				.or(s -> s.like("doc_name", "%.fbx"))
				.or(s -> s.like("doc_name", "%.dxf"))
				.or(s -> s.like("doc_name", "%.skp"))
				.or(s -> s.like("doc_name", "%.ifc"))
				.or(s -> s.like("doc_name", "%.dgn"))
				.or(s -> s.like("doc_name", "%.obj"))
				.or(s -> s.like("doc_name", "%.stl"))
				.or(s -> s.like("doc_name", "%.3ds"))
				.or(s -> s.like("doc_name", "%.dae"))
				.or(s -> s.like("doc_name", "%.ply"))
				.or(s -> s.like("doc_name", "%.igms"))));
		List<DtDoc> docList = docService.list(queryWrapper);
		LOGGER.info("扫描到{}个文件需要获取解析状态", docList.size());
		Map<String, Object> headers = new HashMap<>();
		headers.put("Authorization", String.format("%s %s", "bearer", beamfaceAccesstokenService.getAccesstoken()));
		for (DtDoc dtDoc : docList) {
			String bimFileId = dtDoc.getBimFileId();
			Map<String, Object> params = new HashMap<>();
			params.put("fileId", bimFileId);
			try {
				String convertResult = HttpClientUtil.httpGetRequest(GET_CONVERT_URL, headers, params);
				if (convertResult == null) {
					LOGGER.error("获取转换状态失败");
					continue;
				}
				Map<String, Object> converResultJson = (Map<String, Object>) JSONUtils.parse(convertResult);
				String code = converResultJson.get("code").toString();
				if ("success".equals(code)) {
					LOGGER.info("获取转换状态成功");
					Map<String, Object> dataMap = (Map<String, Object>) converResultJson.get("data");
					String status = dataMap.get("status").toString();
					if ("success".equals(status)) {
						LOGGER.info("模型{}的状态:成功", dtDoc.getDocName());
						dtDoc.setStatus(3);
						docService.updateById(dtDoc);
						continue;
					}
				} else {
					LOGGER.error("获取转换状态失败");
					continue;
				}
			} catch (URISyntaxException e) {
				LOGGER.error("获取转换状态失败");
				LOGGER.error(e.getMessage(), e);
				continue;
			}
		}

根据bimface文件ID获取模型viewtoken, 获取到viewtoken就可以利用前端浏览模型或图纸了

public static final String GET_VIEW_TOKEN_URL = "https://api.bimface.com/view/token";

public String getViewToken(SysBeamfaceModelViewtoken beamfaceModelViewtoken) {
		QueryWrapper<SysBeamfaceModelViewtoken> queryWrapper = new QueryWrapper<>(beamfaceModelViewtoken);
		SysBeamfaceModelViewtoken sysBeamfaceModelViewtoken = getOne(queryWrapper);
		if (sysBeamfaceModelViewtoken == null) {
			sysBeamfaceModelViewtoken = new SysBeamfaceModelViewtoken();
			String viewToken = getToken(beamfaceModelViewtoken);
			sysBeamfaceModelViewtoken.setViewToken(viewToken);
			sysBeamfaceModelViewtoken.setCompareid(beamfaceModelViewtoken.getCompareid());
			sysBeamfaceModelViewtoken.setFileid(beamfaceModelViewtoken.getFileid());
			sysBeamfaceModelViewtoken.setIntegrateid(beamfaceModelViewtoken.getIntegrateid());
			// 过期时间为12个小时 保留10分钟误差
			long ts = DateUtils.getMillis() + 60 * 1000 * 60 * 12 - 60 * 1000 * 10;
			sysBeamfaceModelViewtoken.setExpiretimets(Long.toString(ts));
			save(sysBeamfaceModelViewtoken);
		} else {
			long ts = Long.valueOf(sysBeamfaceModelViewtoken.getExpiretimets());
			long currentTs = DateUtils.getMillis();
			if (currentTs > ts) {
				String viewToken = getToken(beamfaceModelViewtoken);
				sysBeamfaceModelViewtoken.setViewToken(viewToken);
				long nts = DateUtils.getMillis() + 60 * 1000 * 60 * 12 - 60 * 1000 * 10;
				sysBeamfaceModelViewtoken.setExpiretimets(Long.toString(nts));
				updateById(sysBeamfaceModelViewtoken);
			}
		}
		return sysBeamfaceModelViewtoken.getViewToken();
	}
	
	@SuppressWarnings("unchecked")
	public String getToken(SysBeamfaceModelViewtoken beamfaceModelViewtoken) {
		// "Authorization: Bearer dc671840-bacc-4dc5-a134-97c1918d664b"
		String accessToken = beamfaceAccesstokenService.getAccesstoken();
		String authorization = String.format("%s %s", "Bearer", accessToken);
		Map<String, Object> headers = new HashMap<>();
		headers.put("Authorization", authorization);
		Map<String, Object> params = new HashMap<>();
		if (!StringUtils.isEmpty(beamfaceModelViewtoken.getCompareid())) {
			params.put("compareId", beamfaceModelViewtoken.getCompareid());
		}
		if (!StringUtils.isEmpty(beamfaceModelViewtoken.getFileid())) {
			params.put("fileId", beamfaceModelViewtoken.getFileid());
		}
		if (!StringUtils.isEmpty(beamfaceModelViewtoken.getIntegrateid())) {
			params.put("integrateId", beamfaceModelViewtoken.getIntegrateid());
		}
		String result = null;
		try {
			result = HttpClientUtil.httpGetRequest(GET_VIEW_TOKEN_URL, headers, params);
		} catch (URISyntaxException e) {
			logger.error(e.getMessage(), e);
			logger.error("获取view token失败");
		}
		if (result == null) {
			logger.error("获取view token失败");
			return null;
		}
		Map<String, Object> map = (Map<String, Object>) JSONUtils.parse(result);
		logger.info("{}", map);
		String success = (String) map.get("code");
		if (!"success".equals(success)) {
			logger.info("请求token失败");
			throw new JeecgBootException("请求模型 view token失败");
		} else {
			return map.get("data").toString();
		}
	}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!要通过Bimface的API来获取对应相机位置的模型截图,您可以按照以下步骤进行操作: 1. 首先,您需要获取Bimface的Access Token。您可以使用OAuth2.0授权方式来获取Access Token,详细信息可以参考Bimface的开发文档。 2. 一旦您获得了Access Token,您可以使用Bimface提供的API来获取模型信息和相机位置。您可以使用以下API来获取模型列表和相机位置信息: - 获取文件列表:GET /view/token/{文件token}/files - 获取模型相机位置:GET /view/token/{文件token}/camera 3. 通过上述API,您可以获取模型的相机位置信息。请注意,相机位置信息包括相机的位置、方向和焦距等信息。 4. 接下来,您可以使用Bimface提供的截图API来获取特定相机位置的模型截图。您可以使用以下API来获取模型截图: - 获取模型截图:GET /snapshot/{文件token}/{构件ID} 在此API中,您需要提供文件的token和构件ID。您可以使用前面获取到的相机位置信息中的参数来构建请求URL。 5. 发起截图请求后,Bimface将会返回您请求的模型截图。您可以根据返回的截图数据进行展示或保存等操作。 这就是通过Bimface的API来获取对应相机位置的模型截图的基本步骤。请注意,具体的实现方式可能会因您所使用的编程语言和框架而有所不同。您可以参考Bimface提供的详细文档和示例代码来进行开发。希望对您有所帮助!如果您还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值